]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/ln/functional_tests.rs
Consider commitment tx fee while assembling a route
[rust-lightning] / lightning / src / ln / functional_tests.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
13
14 use crate::chain;
15 use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Listen, Watch};
16 use crate::chain::chaininterface::LowerBoundedFeeEstimator;
17 use crate::chain::channelmonitor;
18 use crate::chain::channelmonitor::{CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
19 use crate::chain::transaction::OutPoint;
20 use crate::sign::{ChannelSigner, EcdsaChannelSigner, EntropySource};
21 use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose, ClosureReason, HTLCDestination, PaymentFailureReason};
22 use crate::ln::{PaymentPreimage, PaymentSecret, PaymentHash};
23 use crate::ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT};
24 use crate::ln::channelmanager::{self, PaymentId, RAACommitmentOrder, PaymentSendFailure, RecipientOnionFields, BREAKDOWN_TIMEOUT, ENABLE_GOSSIP_TICKS, DISABLE_GOSSIP_TICKS, MIN_CLTV_EXPIRY_DELTA};
25 use crate::ln::channel::{Channel, ChannelError};
26 use crate::ln::{chan_utils, onion_utils};
27 use crate::ln::chan_utils::{OFFERED_HTLC_SCRIPT_WEIGHT, htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
28 use crate::routing::gossip::{NetworkGraph, NetworkUpdate};
29 use crate::routing::router::{Path, PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
30 use crate::ln::features::{ChannelFeatures, NodeFeatures};
31 use crate::ln::msgs;
32 use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
33 use crate::util::enforcing_trait_impls::EnforcingSigner;
34 use crate::util::test_utils;
35 use crate::util::errors::APIError;
36 use crate::util::ser::{Writeable, ReadableArgs};
37 use crate::util::string::UntrustedString;
38 use crate::util::config::UserConfig;
39
40 use bitcoin::hash_types::BlockHash;
41 use bitcoin::blockdata::script::{Builder, Script};
42 use bitcoin::blockdata::opcodes;
43 use bitcoin::blockdata::constants::genesis_block;
44 use bitcoin::network::constants::Network;
45 use bitcoin::{PackedLockTime, Sequence, Transaction, TxIn, TxOut, Witness};
46 use bitcoin::OutPoint as BitcoinOutPoint;
47
48 use bitcoin::secp256k1::Secp256k1;
49 use bitcoin::secp256k1::{PublicKey,SecretKey};
50
51 use regex;
52
53 use crate::io;
54 use crate::prelude::*;
55 use alloc::collections::BTreeSet;
56 use core::default::Default;
57 use core::iter::repeat;
58 use bitcoin::hashes::Hash;
59 use crate::sync::{Arc, Mutex};
60
61 use crate::ln::functional_test_utils::*;
62 use crate::ln::chan_utils::CommitmentTransaction;
63
64 #[test]
65 fn test_insane_channel_opens() {
66         // Stand up a network of 2 nodes
67         use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
68         let mut cfg = UserConfig::default();
69         cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
70         let chanmon_cfgs = create_chanmon_cfgs(2);
71         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
72         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
73         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
74
75         // Instantiate channel parameters where we push the maximum msats given our
76         // funding satoshis
77         let channel_value_sat = 31337; // same as funding satoshis
78         let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
79         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
80
81         // Have node0 initiate a channel to node1 with aforementioned parameters
82         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
83
84         // Extract the channel open message from node0 to node1
85         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
86
87         // Test helper that asserts we get the correct error string given a mutator
88         // that supposedly makes the channel open message insane
89         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
90                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &message_mutator(open_channel_message.clone()));
91                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
92                 assert_eq!(msg_events.len(), 1);
93                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
94                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
95                         match action {
96                                 &ErrorAction::SendErrorMessage { .. } => {
97                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager", expected_regex, 1);
98                                 },
99                                 _ => panic!("unexpected event!"),
100                         }
101                 } else { assert!(false); }
102         };
103
104         use crate::ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
105
106         // Test all mutations that would make the channel open message insane
107         insane_open_helper(format!("Per our config, funding must be at most {}. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1, TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2; msg });
108         insane_open_helper(format!("Funding must be smaller than the total bitcoin supply. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS; msg });
109
110         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
111
112         insane_open_helper(r"push_msat \d+ was larger than channel amount minus reserve \(\d+\)", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
113
114         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
115
116         insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
117
118         insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
119
120         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
121
122         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
123 }
124
125 #[test]
126 fn test_funding_exceeds_no_wumbo_limit() {
127         // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
128         // them.
129         use crate::ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
130         let chanmon_cfgs = create_chanmon_cfgs(2);
131         let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
132         *node_cfgs[1].override_init_features.borrow_mut() = Some(channelmanager::provided_init_features(&test_default_channel_config()).clear_wumbo());
133         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
134         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
135
136         match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
137                 Err(APIError::APIMisuseError { err }) => {
138                         assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
139                 },
140                 _ => panic!()
141         }
142 }
143
144 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
145         // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
146         // but only for them. Because some LSPs do it with some level of trust of the clients (for a
147         // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
148         // in normal testing, we test it explicitly here.
149         let chanmon_cfgs = create_chanmon_cfgs(2);
150         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
151         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
152         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
153         let default_config = UserConfig::default();
154
155         // Have node0 initiate a channel to node1 with aforementioned parameters
156         let mut push_amt = 100_000_000;
157         let feerate_per_kw = 253;
158         let opt_anchors = false;
159         push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
160         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
161
162         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, if send_from_initiator { 0 } else { push_amt }, 42, None).unwrap();
163         let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
164         if !send_from_initiator {
165                 open_channel_message.channel_reserve_satoshis = 0;
166                 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
167         }
168         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
169
170         // Extract the channel accept message from node1 to node0
171         let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
172         if send_from_initiator {
173                 accept_channel_message.channel_reserve_satoshis = 0;
174                 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
175         }
176         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
177         {
178                 let sender_node = if send_from_initiator { &nodes[1] } else { &nodes[0] };
179                 let counterparty_node = if send_from_initiator { &nodes[0] } else { &nodes[1] };
180                 let mut sender_node_per_peer_lock;
181                 let mut sender_node_peer_state_lock;
182                 let mut chan = get_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
183                 chan.holder_selected_channel_reserve_satoshis = 0;
184                 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
185         }
186
187         let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
188         let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
189         create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
190
191         // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
192         // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
193         if send_from_initiator {
194                 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
195                         // Note that for outbound channels we have to consider the commitment tx fee and the
196                         // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
197                         // well as an additional HTLC.
198                         - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
199         } else {
200                 send_payment(&nodes[1], &[&nodes[0]], push_amt);
201         }
202 }
203
204 #[test]
205 fn test_counterparty_no_reserve() {
206         do_test_counterparty_no_reserve(true);
207         do_test_counterparty_no_reserve(false);
208 }
209
210 #[test]
211 fn test_async_inbound_update_fee() {
212         let chanmon_cfgs = create_chanmon_cfgs(2);
213         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
214         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
215         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
216         create_announced_chan_between_nodes(&nodes, 0, 1);
217
218         // balancing
219         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
220
221         // A                                        B
222         // update_fee                            ->
223         // send (1) commitment_signed            -.
224         //                                       <- update_add_htlc/commitment_signed
225         // send (2) RAA (awaiting remote revoke) -.
226         // (1) commitment_signed is delivered    ->
227         //                                       .- send (3) RAA (awaiting remote revoke)
228         // (2) RAA is delivered                  ->
229         //                                       .- send (4) commitment_signed
230         //                                       <- (3) RAA is delivered
231         // send (5) commitment_signed            -.
232         //                                       <- (4) commitment_signed is delivered
233         // send (6) RAA                          -.
234         // (5) commitment_signed is delivered    ->
235         //                                       <- RAA
236         // (6) RAA is delivered                  ->
237
238         // First nodes[0] generates an update_fee
239         {
240                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
241                 *feerate_lock += 20;
242         }
243         nodes[0].node.timer_tick_occurred();
244         check_added_monitors!(nodes[0], 1);
245
246         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
247         assert_eq!(events_0.len(), 1);
248         let (update_msg, commitment_signed) = match events_0[0] { // (1)
249                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
250                         (update_fee.as_ref(), commitment_signed)
251                 },
252                 _ => panic!("Unexpected event"),
253         };
254
255         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
256
257         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
258         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
259         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
260                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
261         check_added_monitors!(nodes[1], 1);
262
263         let payment_event = {
264                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
265                 assert_eq!(events_1.len(), 1);
266                 SendEvent::from_event(events_1.remove(0))
267         };
268         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
269         assert_eq!(payment_event.msgs.len(), 1);
270
271         // ...now when the messages get delivered everyone should be happy
272         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
273         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
274         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
275         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
276         check_added_monitors!(nodes[0], 1);
277
278         // deliver(1), generate (3):
279         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
280         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
281         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
282         check_added_monitors!(nodes[1], 1);
283
284         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
285         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
286         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
287         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
288         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
289         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
290         assert!(bs_update.update_fee.is_none()); // (4)
291         check_added_monitors!(nodes[1], 1);
292
293         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
294         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
295         assert!(as_update.update_add_htlcs.is_empty()); // (5)
296         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
297         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
298         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
299         assert!(as_update.update_fee.is_none()); // (5)
300         check_added_monitors!(nodes[0], 1);
301
302         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
303         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
304         // only (6) so get_event_msg's assert(len == 1) passes
305         check_added_monitors!(nodes[0], 1);
306
307         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
308         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
309         check_added_monitors!(nodes[1], 1);
310
311         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
312         check_added_monitors!(nodes[0], 1);
313
314         let events_2 = nodes[0].node.get_and_clear_pending_events();
315         assert_eq!(events_2.len(), 1);
316         match events_2[0] {
317                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
318                 _ => panic!("Unexpected event"),
319         }
320
321         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
322         check_added_monitors!(nodes[1], 1);
323 }
324
325 #[test]
326 fn test_update_fee_unordered_raa() {
327         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
328         // crash in an earlier version of the update_fee patch)
329         let chanmon_cfgs = create_chanmon_cfgs(2);
330         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
331         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
332         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
333         create_announced_chan_between_nodes(&nodes, 0, 1);
334
335         // balancing
336         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
337
338         // First nodes[0] generates an update_fee
339         {
340                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
341                 *feerate_lock += 20;
342         }
343         nodes[0].node.timer_tick_occurred();
344         check_added_monitors!(nodes[0], 1);
345
346         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
347         assert_eq!(events_0.len(), 1);
348         let update_msg = match events_0[0] { // (1)
349                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
350                         update_fee.as_ref()
351                 },
352                 _ => panic!("Unexpected event"),
353         };
354
355         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
356
357         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
358         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
359         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
360                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
361         check_added_monitors!(nodes[1], 1);
362
363         let payment_event = {
364                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
365                 assert_eq!(events_1.len(), 1);
366                 SendEvent::from_event(events_1.remove(0))
367         };
368         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
369         assert_eq!(payment_event.msgs.len(), 1);
370
371         // ...now when the messages get delivered everyone should be happy
372         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
373         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
374         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
375         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
376         check_added_monitors!(nodes[0], 1);
377
378         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
379         check_added_monitors!(nodes[1], 1);
380
381         // We can't continue, sadly, because our (1) now has a bogus signature
382 }
383
384 #[test]
385 fn test_multi_flight_update_fee() {
386         let chanmon_cfgs = create_chanmon_cfgs(2);
387         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
388         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
389         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
390         create_announced_chan_between_nodes(&nodes, 0, 1);
391
392         // A                                        B
393         // update_fee/commitment_signed          ->
394         //                                       .- send (1) RAA and (2) commitment_signed
395         // update_fee (never committed)          ->
396         // (3) update_fee                        ->
397         // We have to manually generate the above update_fee, it is allowed by the protocol but we
398         // don't track which updates correspond to which revoke_and_ack responses so we're in
399         // AwaitingRAA mode and will not generate the update_fee yet.
400         //                                       <- (1) RAA delivered
401         // (3) is generated and send (4) CS      -.
402         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
403         // know the per_commitment_point to use for it.
404         //                                       <- (2) commitment_signed delivered
405         // revoke_and_ack                        ->
406         //                                          B should send no response here
407         // (4) commitment_signed delivered       ->
408         //                                       <- RAA/commitment_signed delivered
409         // revoke_and_ack                        ->
410
411         // First nodes[0] generates an update_fee
412         let initial_feerate;
413         {
414                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
415                 initial_feerate = *feerate_lock;
416                 *feerate_lock = initial_feerate + 20;
417         }
418         nodes[0].node.timer_tick_occurred();
419         check_added_monitors!(nodes[0], 1);
420
421         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
422         assert_eq!(events_0.len(), 1);
423         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
424                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
425                         (update_fee.as_ref().unwrap(), commitment_signed)
426                 },
427                 _ => panic!("Unexpected event"),
428         };
429
430         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
431         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
432         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
433         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
434         check_added_monitors!(nodes[1], 1);
435
436         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
437         // transaction:
438         {
439                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
440                 *feerate_lock = initial_feerate + 40;
441         }
442         nodes[0].node.timer_tick_occurred();
443         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
444         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
445
446         // Create the (3) update_fee message that nodes[0] will generate before it does...
447         let mut update_msg_2 = msgs::UpdateFee {
448                 channel_id: update_msg_1.channel_id.clone(),
449                 feerate_per_kw: (initial_feerate + 30) as u32,
450         };
451
452         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
453
454         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
455         // Deliver (3)
456         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
457
458         // Deliver (1), generating (3) and (4)
459         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
460         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
461         check_added_monitors!(nodes[0], 1);
462         assert!(as_second_update.update_add_htlcs.is_empty());
463         assert!(as_second_update.update_fulfill_htlcs.is_empty());
464         assert!(as_second_update.update_fail_htlcs.is_empty());
465         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
466         // Check that the update_fee newly generated matches what we delivered:
467         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
468         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
469
470         // Deliver (2) commitment_signed
471         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
472         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
473         check_added_monitors!(nodes[0], 1);
474         // No commitment_signed so get_event_msg's assert(len == 1) passes
475
476         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
477         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
478         check_added_monitors!(nodes[1], 1);
479
480         // Delever (4)
481         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
482         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
483         check_added_monitors!(nodes[1], 1);
484
485         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
486         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
487         check_added_monitors!(nodes[0], 1);
488
489         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
490         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
491         // No commitment_signed so get_event_msg's assert(len == 1) passes
492         check_added_monitors!(nodes[0], 1);
493
494         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
495         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
496         check_added_monitors!(nodes[1], 1);
497 }
498
499 fn do_test_sanity_on_in_flight_opens(steps: u8) {
500         // Previously, we had issues deserializing channels when we hadn't connected the first block
501         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
502         // serialization round-trips and simply do steps towards opening a channel and then drop the
503         // Node objects.
504
505         let chanmon_cfgs = create_chanmon_cfgs(2);
506         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
507         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
508         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
509
510         if steps & 0b1000_0000 != 0{
511                 let block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
512                 connect_block(&nodes[0], &block);
513                 connect_block(&nodes[1], &block);
514         }
515
516         if steps & 0x0f == 0 { return; }
517         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
518         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
519
520         if steps & 0x0f == 1 { return; }
521         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
522         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
523
524         if steps & 0x0f == 2 { return; }
525         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
526
527         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
528
529         if steps & 0x0f == 3 { return; }
530         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
531         check_added_monitors!(nodes[0], 0);
532         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
533
534         if steps & 0x0f == 4 { return; }
535         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
536         {
537                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
538                 assert_eq!(added_monitors.len(), 1);
539                 assert_eq!(added_monitors[0].0, funding_output);
540                 added_monitors.clear();
541         }
542         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
543
544         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
545
546         if steps & 0x0f == 5 { return; }
547         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
548         {
549                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
550                 assert_eq!(added_monitors.len(), 1);
551                 assert_eq!(added_monitors[0].0, funding_output);
552                 added_monitors.clear();
553         }
554
555         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
556         let events_4 = nodes[0].node.get_and_clear_pending_events();
557         assert_eq!(events_4.len(), 0);
558
559         if steps & 0x0f == 6 { return; }
560         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
561
562         if steps & 0x0f == 7 { return; }
563         confirm_transaction_at(&nodes[0], &tx, 2);
564         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
565         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
566         expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
567 }
568
569 #[test]
570 fn test_sanity_on_in_flight_opens() {
571         do_test_sanity_on_in_flight_opens(0);
572         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
573         do_test_sanity_on_in_flight_opens(1);
574         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
575         do_test_sanity_on_in_flight_opens(2);
576         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
577         do_test_sanity_on_in_flight_opens(3);
578         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
579         do_test_sanity_on_in_flight_opens(4);
580         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
581         do_test_sanity_on_in_flight_opens(5);
582         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
583         do_test_sanity_on_in_flight_opens(6);
584         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
585         do_test_sanity_on_in_flight_opens(7);
586         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
587         do_test_sanity_on_in_flight_opens(8);
588         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
589 }
590
591 #[test]
592 fn test_update_fee_vanilla() {
593         let chanmon_cfgs = create_chanmon_cfgs(2);
594         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
595         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
596         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
597         create_announced_chan_between_nodes(&nodes, 0, 1);
598
599         {
600                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
601                 *feerate_lock += 25;
602         }
603         nodes[0].node.timer_tick_occurred();
604         check_added_monitors!(nodes[0], 1);
605
606         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
607         assert_eq!(events_0.len(), 1);
608         let (update_msg, commitment_signed) = match events_0[0] {
609                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
610                         (update_fee.as_ref(), commitment_signed)
611                 },
612                 _ => panic!("Unexpected event"),
613         };
614         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
615
616         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
617         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
618         check_added_monitors!(nodes[1], 1);
619
620         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
621         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
622         check_added_monitors!(nodes[0], 1);
623
624         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
625         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
626         // No commitment_signed so get_event_msg's assert(len == 1) passes
627         check_added_monitors!(nodes[0], 1);
628
629         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
630         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
631         check_added_monitors!(nodes[1], 1);
632 }
633
634 #[test]
635 fn test_update_fee_that_funder_cannot_afford() {
636         let chanmon_cfgs = create_chanmon_cfgs(2);
637         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
638         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
639         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
640         let channel_value = 5000;
641         let push_sats = 700;
642         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000);
643         let channel_id = chan.2;
644         let secp_ctx = Secp256k1::new();
645         let default_config = UserConfig::default();
646         let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
647
648         let opt_anchors = false;
649
650         // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
651         // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
652         // calculate two different feerates here - the expected local limit as well as the expected
653         // remote limit.
654         let feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / (commitment_tx_base_weight(opt_anchors) + CONCURRENT_INBOUND_HTLC_FEE_BUFFER as u64 * COMMITMENT_TX_WEIGHT_PER_HTLC)) as u32;
655         let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
656         {
657                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
658                 *feerate_lock = feerate;
659         }
660         nodes[0].node.timer_tick_occurred();
661         check_added_monitors!(nodes[0], 1);
662         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
663
664         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
665
666         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
667
668         // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
669         {
670                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
671
672                 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
673                 assert_eq!(commitment_tx.output.len(), 2);
674                 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
675                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
676                 actual_fee = channel_value - actual_fee;
677                 assert_eq!(total_fee, actual_fee);
678         }
679
680         {
681                 // Increment the feerate by a small constant, accounting for rounding errors
682                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
683                 *feerate_lock += 4;
684         }
685         nodes[0].node.timer_tick_occurred();
686         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
687         check_added_monitors!(nodes[0], 0);
688
689         const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
690
691         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
692         // needed to sign the new commitment tx and (2) sign the new commitment tx.
693         let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
694                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
695                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
696                 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
697                 let chan_signer = local_chan.get_signer();
698                 let pubkeys = chan_signer.pubkeys();
699                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
700                  pubkeys.funding_pubkey)
701         };
702         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
703                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
704                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
705                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
706                 let chan_signer = remote_chan.get_signer();
707                 let pubkeys = chan_signer.pubkeys();
708                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
709                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
710                  pubkeys.funding_pubkey)
711         };
712
713         // Assemble the set of keys we can use for signatures for our commitment_signed message.
714         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
715                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
716
717         let res = {
718                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
719                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
720                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
721                 let local_chan_signer = local_chan.get_signer();
722                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
723                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
724                         INITIAL_COMMITMENT_NUMBER - 1,
725                         push_sats,
726                         channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
727                         opt_anchors, local_funding, remote_funding,
728                         commit_tx_keys.clone(),
729                         non_buffer_feerate + 4,
730                         &mut htlcs,
731                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
732                 );
733                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
734         };
735
736         let commit_signed_msg = msgs::CommitmentSigned {
737                 channel_id: chan.2,
738                 signature: res.0,
739                 htlc_signatures: res.1,
740                 #[cfg(taproot)]
741                 partial_signature_with_nonce: None,
742         };
743
744         let update_fee = msgs::UpdateFee {
745                 channel_id: chan.2,
746                 feerate_per_kw: non_buffer_feerate + 4,
747         };
748
749         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
750
751         //While producing the commitment_signed response after handling a received update_fee request the
752         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
753         //Should produce and error.
754         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
755         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
756         check_added_monitors!(nodes[1], 1);
757         check_closed_broadcast!(nodes[1], true);
758         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
759 }
760
761 #[test]
762 fn test_update_fee_with_fundee_update_add_htlc() {
763         let chanmon_cfgs = create_chanmon_cfgs(2);
764         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
765         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
766         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
767         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
768
769         // balancing
770         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
771
772         {
773                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
774                 *feerate_lock += 20;
775         }
776         nodes[0].node.timer_tick_occurred();
777         check_added_monitors!(nodes[0], 1);
778
779         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
780         assert_eq!(events_0.len(), 1);
781         let (update_msg, commitment_signed) = match events_0[0] {
782                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
783                         (update_fee.as_ref(), commitment_signed)
784                 },
785                 _ => panic!("Unexpected event"),
786         };
787         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
788         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
789         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
790         check_added_monitors!(nodes[1], 1);
791
792         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
793
794         // nothing happens since node[1] is in AwaitingRemoteRevoke
795         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
796                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
797         {
798                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
799                 assert_eq!(added_monitors.len(), 0);
800                 added_monitors.clear();
801         }
802         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
803         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
804         // node[1] has nothing to do
805
806         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
807         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
808         check_added_monitors!(nodes[0], 1);
809
810         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
811         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
812         // No commitment_signed so get_event_msg's assert(len == 1) passes
813         check_added_monitors!(nodes[0], 1);
814         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
815         check_added_monitors!(nodes[1], 1);
816         // AwaitingRemoteRevoke ends here
817
818         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
819         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
820         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
821         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
822         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
823         assert_eq!(commitment_update.update_fee.is_none(), true);
824
825         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
826         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
827         check_added_monitors!(nodes[0], 1);
828         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
829
830         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
831         check_added_monitors!(nodes[1], 1);
832         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
833
834         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
835         check_added_monitors!(nodes[1], 1);
836         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
837         // No commitment_signed so get_event_msg's assert(len == 1) passes
838
839         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
840         check_added_monitors!(nodes[0], 1);
841         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
842
843         expect_pending_htlcs_forwardable!(nodes[0]);
844
845         let events = nodes[0].node.get_and_clear_pending_events();
846         assert_eq!(events.len(), 1);
847         match events[0] {
848                 Event::PaymentClaimable { .. } => { },
849                 _ => panic!("Unexpected event"),
850         };
851
852         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
853
854         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
855         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
856         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
857         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
858         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
859 }
860
861 #[test]
862 fn test_update_fee() {
863         let chanmon_cfgs = create_chanmon_cfgs(2);
864         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
865         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
866         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
867         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
868         let channel_id = chan.2;
869
870         // A                                        B
871         // (1) update_fee/commitment_signed      ->
872         //                                       <- (2) revoke_and_ack
873         //                                       .- send (3) commitment_signed
874         // (4) update_fee/commitment_signed      ->
875         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
876         //                                       <- (3) commitment_signed delivered
877         // send (6) revoke_and_ack               -.
878         //                                       <- (5) deliver revoke_and_ack
879         // (6) deliver revoke_and_ack            ->
880         //                                       .- send (7) commitment_signed in response to (4)
881         //                                       <- (7) deliver commitment_signed
882         // revoke_and_ack                        ->
883
884         // Create and deliver (1)...
885         let feerate;
886         {
887                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
888                 feerate = *feerate_lock;
889                 *feerate_lock = feerate + 20;
890         }
891         nodes[0].node.timer_tick_occurred();
892         check_added_monitors!(nodes[0], 1);
893
894         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
895         assert_eq!(events_0.len(), 1);
896         let (update_msg, commitment_signed) = match events_0[0] {
897                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
898                         (update_fee.as_ref(), commitment_signed)
899                 },
900                 _ => panic!("Unexpected event"),
901         };
902         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
903
904         // Generate (2) and (3):
905         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
906         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
907         check_added_monitors!(nodes[1], 1);
908
909         // Deliver (2):
910         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
911         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
912         check_added_monitors!(nodes[0], 1);
913
914         // Create and deliver (4)...
915         {
916                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
917                 *feerate_lock = feerate + 30;
918         }
919         nodes[0].node.timer_tick_occurred();
920         check_added_monitors!(nodes[0], 1);
921         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
922         assert_eq!(events_0.len(), 1);
923         let (update_msg, commitment_signed) = match events_0[0] {
924                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
925                         (update_fee.as_ref(), commitment_signed)
926                 },
927                 _ => panic!("Unexpected event"),
928         };
929
930         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
931         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
932         check_added_monitors!(nodes[1], 1);
933         // ... creating (5)
934         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
935         // No commitment_signed so get_event_msg's assert(len == 1) passes
936
937         // Handle (3), creating (6):
938         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
939         check_added_monitors!(nodes[0], 1);
940         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
941         // No commitment_signed so get_event_msg's assert(len == 1) passes
942
943         // Deliver (5):
944         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
945         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
946         check_added_monitors!(nodes[0], 1);
947
948         // Deliver (6), creating (7):
949         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
950         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
951         assert!(commitment_update.update_add_htlcs.is_empty());
952         assert!(commitment_update.update_fulfill_htlcs.is_empty());
953         assert!(commitment_update.update_fail_htlcs.is_empty());
954         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
955         assert!(commitment_update.update_fee.is_none());
956         check_added_monitors!(nodes[1], 1);
957
958         // Deliver (7)
959         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
960         check_added_monitors!(nodes[0], 1);
961         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
962         // No commitment_signed so get_event_msg's assert(len == 1) passes
963
964         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
965         check_added_monitors!(nodes[1], 1);
966         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
967
968         assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
969         assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
970         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
971         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
972         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
973 }
974
975 #[test]
976 fn fake_network_test() {
977         // Simple test which builds a network of ChannelManagers, connects them to each other, and
978         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
979         let chanmon_cfgs = create_chanmon_cfgs(4);
980         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
981         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
982         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
983
984         // Create some initial channels
985         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
986         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
987         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
988
989         // Rebalance the network a bit by relaying one payment through all the channels...
990         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
991         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
992         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
993         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
994
995         // Send some more payments
996         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
997         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
998         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
999
1000         // Test failure packets
1001         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1002         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1003
1004         // Add a new channel that skips 3
1005         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1006
1007         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1008         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1009         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1010         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1011         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1012         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1013         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1014
1015         // Do some rebalance loop payments, simultaneously
1016         let mut hops = Vec::with_capacity(3);
1017         hops.push(RouteHop {
1018                 pubkey: nodes[2].node.get_our_node_id(),
1019                 node_features: NodeFeatures::empty(),
1020                 short_channel_id: chan_2.0.contents.short_channel_id,
1021                 channel_features: ChannelFeatures::empty(),
1022                 fee_msat: 0,
1023                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1024         });
1025         hops.push(RouteHop {
1026                 pubkey: nodes[3].node.get_our_node_id(),
1027                 node_features: NodeFeatures::empty(),
1028                 short_channel_id: chan_3.0.contents.short_channel_id,
1029                 channel_features: ChannelFeatures::empty(),
1030                 fee_msat: 0,
1031                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1032         });
1033         hops.push(RouteHop {
1034                 pubkey: nodes[1].node.get_our_node_id(),
1035                 node_features: nodes[1].node.node_features(),
1036                 short_channel_id: chan_4.0.contents.short_channel_id,
1037                 channel_features: nodes[1].node.channel_features(),
1038                 fee_msat: 1000000,
1039                 cltv_expiry_delta: TEST_FINAL_CLTV,
1040         });
1041         hops[1].fee_msat = chan_4.1.contents.fee_base_msat as u64 + chan_4.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1042         hops[0].fee_msat = chan_3.0.contents.fee_base_msat as u64 + chan_3.0.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1043         let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![Path { hops, blinded_tail: None }], payment_params: None }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1044
1045         let mut hops = Vec::with_capacity(3);
1046         hops.push(RouteHop {
1047                 pubkey: nodes[3].node.get_our_node_id(),
1048                 node_features: NodeFeatures::empty(),
1049                 short_channel_id: chan_4.0.contents.short_channel_id,
1050                 channel_features: ChannelFeatures::empty(),
1051                 fee_msat: 0,
1052                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1053         });
1054         hops.push(RouteHop {
1055                 pubkey: nodes[2].node.get_our_node_id(),
1056                 node_features: NodeFeatures::empty(),
1057                 short_channel_id: chan_3.0.contents.short_channel_id,
1058                 channel_features: ChannelFeatures::empty(),
1059                 fee_msat: 0,
1060                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1061         });
1062         hops.push(RouteHop {
1063                 pubkey: nodes[1].node.get_our_node_id(),
1064                 node_features: nodes[1].node.node_features(),
1065                 short_channel_id: chan_2.0.contents.short_channel_id,
1066                 channel_features: nodes[1].node.channel_features(),
1067                 fee_msat: 1000000,
1068                 cltv_expiry_delta: TEST_FINAL_CLTV,
1069         });
1070         hops[1].fee_msat = chan_2.1.contents.fee_base_msat as u64 + chan_2.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1071         hops[0].fee_msat = chan_3.1.contents.fee_base_msat as u64 + chan_3.1.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1072         let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![Path { hops, blinded_tail: None }], payment_params: None }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1073
1074         // Claim the rebalances...
1075         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1076         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1077
1078         // Close down the channels...
1079         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1080         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1081         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1082         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1083         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1084         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1085         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1086         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1087         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1088         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1089         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1090         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1091 }
1092
1093 #[test]
1094 fn holding_cell_htlc_counting() {
1095         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1096         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1097         // commitment dance rounds.
1098         let chanmon_cfgs = create_chanmon_cfgs(3);
1099         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1100         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1101         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1102         create_announced_chan_between_nodes(&nodes, 0, 1);
1103         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1104
1105         let mut payments = Vec::new();
1106         for _ in 0..50 {
1107                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1108                 nodes[1].node.send_payment_with_route(&route, payment_hash,
1109                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1110                 payments.push((payment_preimage, payment_hash));
1111         }
1112         check_added_monitors!(nodes[1], 1);
1113
1114         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1115         assert_eq!(events.len(), 1);
1116         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1117         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1118
1119         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1120         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1121         // another HTLC.
1122         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1123         {
1124                 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, payment_hash_1,
1125                                 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)
1126                         ), true, APIError::ChannelUnavailable { ref err },
1127                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1128                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1129                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
1130         }
1131
1132         // This should also be true if we try to forward a payment.
1133         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1134         {
1135                 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1136                         RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1137                 check_added_monitors!(nodes[0], 1);
1138         }
1139
1140         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1141         assert_eq!(events.len(), 1);
1142         let payment_event = SendEvent::from_event(events.pop().unwrap());
1143         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1144
1145         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1146         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1147         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1148         // fails), the second will process the resulting failure and fail the HTLC backward.
1149         expect_pending_htlcs_forwardable!(nodes[1]);
1150         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
1151         check_added_monitors!(nodes[1], 1);
1152
1153         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1154         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1155         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1156
1157         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1158
1159         // Now forward all the pending HTLCs and claim them back
1160         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1161         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1162         check_added_monitors!(nodes[2], 1);
1163
1164         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1165         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1166         check_added_monitors!(nodes[1], 1);
1167         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1168
1169         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1170         check_added_monitors!(nodes[1], 1);
1171         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1172
1173         for ref update in as_updates.update_add_htlcs.iter() {
1174                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1175         }
1176         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1177         check_added_monitors!(nodes[2], 1);
1178         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1179         check_added_monitors!(nodes[2], 1);
1180         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1181
1182         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1183         check_added_monitors!(nodes[1], 1);
1184         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1185         check_added_monitors!(nodes[1], 1);
1186         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1187
1188         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1189         check_added_monitors!(nodes[2], 1);
1190
1191         expect_pending_htlcs_forwardable!(nodes[2]);
1192
1193         let events = nodes[2].node.get_and_clear_pending_events();
1194         assert_eq!(events.len(), payments.len());
1195         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1196                 match event {
1197                         &Event::PaymentClaimable { ref payment_hash, .. } => {
1198                                 assert_eq!(*payment_hash, *hash);
1199                         },
1200                         _ => panic!("Unexpected event"),
1201                 };
1202         }
1203
1204         for (preimage, _) in payments.drain(..) {
1205                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1206         }
1207
1208         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1209 }
1210
1211 #[test]
1212 fn duplicate_htlc_test() {
1213         // Test that we accept duplicate payment_hash HTLCs across the network and that
1214         // claiming/failing them are all separate and don't affect each other
1215         let chanmon_cfgs = create_chanmon_cfgs(6);
1216         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1217         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1218         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1219
1220         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1221         create_announced_chan_between_nodes(&nodes, 0, 3);
1222         create_announced_chan_between_nodes(&nodes, 1, 3);
1223         create_announced_chan_between_nodes(&nodes, 2, 3);
1224         create_announced_chan_between_nodes(&nodes, 3, 4);
1225         create_announced_chan_between_nodes(&nodes, 3, 5);
1226
1227         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1228
1229         *nodes[0].network_payment_count.borrow_mut() -= 1;
1230         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1231
1232         *nodes[0].network_payment_count.borrow_mut() -= 1;
1233         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1234
1235         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1236         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1237         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1238 }
1239
1240 #[test]
1241 fn test_duplicate_htlc_different_direction_onchain() {
1242         // Test that ChannelMonitor doesn't generate 2 preimage txn
1243         // when we have 2 HTLCs with same preimage that go across a node
1244         // in opposite directions, even with the same payment secret.
1245         let chanmon_cfgs = create_chanmon_cfgs(2);
1246         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1247         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1248         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1249
1250         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1251
1252         // balancing
1253         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1254
1255         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1256
1257         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1258         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1259         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1260
1261         // Provide preimage to node 0 by claiming payment
1262         nodes[0].node.claim_funds(payment_preimage);
1263         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1264         check_added_monitors!(nodes[0], 1);
1265
1266         // Broadcast node 1 commitment txn
1267         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1268
1269         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1270         let mut has_both_htlcs = 0; // check htlcs match ones committed
1271         for outp in remote_txn[0].output.iter() {
1272                 if outp.value == 800_000 / 1000 {
1273                         has_both_htlcs += 1;
1274                 } else if outp.value == 900_000 / 1000 {
1275                         has_both_htlcs += 1;
1276                 }
1277         }
1278         assert_eq!(has_both_htlcs, 2);
1279
1280         mine_transaction(&nodes[0], &remote_txn[0]);
1281         check_added_monitors!(nodes[0], 1);
1282         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1283         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
1284
1285         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1286         assert_eq!(claim_txn.len(), 3);
1287
1288         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1289         check_spends!(claim_txn[1], remote_txn[0]);
1290         check_spends!(claim_txn[2], remote_txn[0]);
1291         let preimage_tx = &claim_txn[0];
1292         let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1293                 (&claim_txn[1], &claim_txn[2])
1294         } else {
1295                 (&claim_txn[2], &claim_txn[1])
1296         };
1297
1298         assert_eq!(preimage_tx.input.len(), 1);
1299         assert_eq!(preimage_bump_tx.input.len(), 1);
1300
1301         assert_eq!(preimage_tx.input.len(), 1);
1302         assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1303         assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1304
1305         assert_eq!(timeout_tx.input.len(), 1);
1306         assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1307         check_spends!(timeout_tx, remote_txn[0]);
1308         assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1309
1310         let events = nodes[0].node.get_and_clear_pending_msg_events();
1311         assert_eq!(events.len(), 3);
1312         for e in events {
1313                 match e {
1314                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1315                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1316                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1317                                 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1318                         },
1319                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
1320                                 assert!(update_add_htlcs.is_empty());
1321                                 assert!(update_fail_htlcs.is_empty());
1322                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1323                                 assert!(update_fail_malformed_htlcs.is_empty());
1324                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1325                         },
1326                         _ => panic!("Unexpected event"),
1327                 }
1328         }
1329 }
1330
1331 #[test]
1332 fn test_basic_channel_reserve() {
1333         let chanmon_cfgs = create_chanmon_cfgs(2);
1334         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1335         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1336         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1337         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1338
1339         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1340         let channel_reserve = chan_stat.channel_reserve_msat;
1341
1342         // The 2* and +1 are for the fee spike reserve.
1343         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], nodes[1], chan.2), 1 + 1, get_opt_anchors!(nodes[0], nodes[1], chan.2));
1344         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1345         let (mut route, our_payment_hash, _, our_payment_secret) =
1346                 get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
1347         route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1348         let err = nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1349                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1350         match err {
1351                 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1352                         match &fails[0] {
1353                                 &APIError::ChannelUnavailable{ref err} =>
1354                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1355                                 _ => panic!("Unexpected error variant"),
1356                         }
1357                 },
1358                 _ => panic!("Unexpected error variant"),
1359         }
1360         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1361         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put our balance under counterparty-announced channel reserve value", 1);
1362
1363         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1364 }
1365
1366 #[test]
1367 fn test_fee_spike_violation_fails_htlc() {
1368         let chanmon_cfgs = create_chanmon_cfgs(2);
1369         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1370         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1371         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1372         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1373
1374         let (mut route, payment_hash, _, payment_secret) =
1375                 get_route_and_payment_hash!(nodes[0], nodes[1], 3460000);
1376         route.paths[0].hops[0].fee_msat += 1;
1377         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1378         let secp_ctx = Secp256k1::new();
1379         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1380
1381         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1382
1383         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1384         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1385                 3460001, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1386         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1387         let msg = msgs::UpdateAddHTLC {
1388                 channel_id: chan.2,
1389                 htlc_id: 0,
1390                 amount_msat: htlc_msat,
1391                 payment_hash: payment_hash,
1392                 cltv_expiry: htlc_cltv,
1393                 onion_routing_packet: onion_packet,
1394         };
1395
1396         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1397
1398         // Now manually create the commitment_signed message corresponding to the update_add
1399         // nodes[0] just sent. In the code for construction of this message, "local" refers
1400         // to the sender of the message, and "remote" refers to the receiver.
1401
1402         let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1403
1404         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1405
1406         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1407         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1408         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1409                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1410                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1411                 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1412                 let chan_signer = local_chan.get_signer();
1413                 // Make the signer believe we validated another commitment, so we can release the secret
1414                 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1415
1416                 let pubkeys = chan_signer.pubkeys();
1417                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1418                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1419                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1420                  chan_signer.pubkeys().funding_pubkey)
1421         };
1422         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1423                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1424                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1425                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1426                 let chan_signer = remote_chan.get_signer();
1427                 let pubkeys = chan_signer.pubkeys();
1428                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1429                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1430                  chan_signer.pubkeys().funding_pubkey)
1431         };
1432
1433         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1434         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1435                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1436
1437         // Build the remote commitment transaction so we can sign it, and then later use the
1438         // signature for the commitment_signed message.
1439         let local_chan_balance = 1313;
1440
1441         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1442                 offered: false,
1443                 amount_msat: 3460001,
1444                 cltv_expiry: htlc_cltv,
1445                 payment_hash,
1446                 transaction_output_index: Some(1),
1447         };
1448
1449         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1450
1451         let res = {
1452                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1453                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1454                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
1455                 let local_chan_signer = local_chan.get_signer();
1456                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1457                         commitment_number,
1458                         95000,
1459                         local_chan_balance,
1460                         local_chan.opt_anchors(), local_funding, remote_funding,
1461                         commit_tx_keys.clone(),
1462                         feerate_per_kw,
1463                         &mut vec![(accepted_htlc_info, ())],
1464                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1465                 );
1466                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1467         };
1468
1469         let commit_signed_msg = msgs::CommitmentSigned {
1470                 channel_id: chan.2,
1471                 signature: res.0,
1472                 htlc_signatures: res.1,
1473                 #[cfg(taproot)]
1474                 partial_signature_with_nonce: None,
1475         };
1476
1477         // Send the commitment_signed message to the nodes[1].
1478         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1479         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1480
1481         // Send the RAA to nodes[1].
1482         let raa_msg = msgs::RevokeAndACK {
1483                 channel_id: chan.2,
1484                 per_commitment_secret: local_secret,
1485                 next_per_commitment_point: next_local_point,
1486                 #[cfg(taproot)]
1487                 next_local_nonce: None,
1488         };
1489         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1490
1491         let events = nodes[1].node.get_and_clear_pending_msg_events();
1492         assert_eq!(events.len(), 1);
1493         // Make sure the HTLC failed in the way we expect.
1494         match events[0] {
1495                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1496                         assert_eq!(update_fail_htlcs.len(), 1);
1497                         update_fail_htlcs[0].clone()
1498                 },
1499                 _ => panic!("Unexpected event"),
1500         };
1501         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1502                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1503
1504         check_added_monitors!(nodes[1], 2);
1505 }
1506
1507 #[test]
1508 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1509         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1510         // Set the fee rate for the channel very high, to the point where the fundee
1511         // sending any above-dust amount would result in a channel reserve violation.
1512         // In this test we check that we would be prevented from sending an HTLC in
1513         // this situation.
1514         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1515         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1516         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1517         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1518         let default_config = UserConfig::default();
1519         let opt_anchors = false;
1520
1521         let mut push_amt = 100_000_000;
1522         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1523
1524         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1525
1526         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1527
1528         // Sending exactly enough to hit the reserve amount should be accepted
1529         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1530                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1531         }
1532
1533         // However one more HTLC should be significantly over the reserve amount and fail.
1534         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1535         unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1536                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1537                 ), true, APIError::ChannelUnavailable { ref err },
1538                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1539         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1540         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put counterparty balance under holder-announced channel reserve value".to_string(), 1);
1541 }
1542
1543 #[test]
1544 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1545         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1546         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1547         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1548         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1549         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1550         let default_config = UserConfig::default();
1551         let opt_anchors = false;
1552
1553         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1554         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1555         // transaction fee with 0 HTLCs (183 sats)).
1556         let mut push_amt = 100_000_000;
1557         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1558         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1559         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1560
1561         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1562         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1563                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1564         }
1565
1566         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1567         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1568         let secp_ctx = Secp256k1::new();
1569         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1570         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1571         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1572         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1573                 700_000, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1574         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1575         let msg = msgs::UpdateAddHTLC {
1576                 channel_id: chan.2,
1577                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1578                 amount_msat: htlc_msat,
1579                 payment_hash: payment_hash,
1580                 cltv_expiry: htlc_cltv,
1581                 onion_routing_packet: onion_packet,
1582         };
1583
1584         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1585         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1586         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);
1587         assert_eq!(nodes[0].node.list_channels().len(), 0);
1588         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1589         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1590         check_added_monitors!(nodes[0], 1);
1591         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() });
1592 }
1593
1594 #[test]
1595 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1596         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1597         // calculating our commitment transaction fee (this was previously broken).
1598         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1599         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1600
1601         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1602         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1603         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1604         let default_config = UserConfig::default();
1605         let opt_anchors = false;
1606
1607         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1608         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1609         // transaction fee with 0 HTLCs (183 sats)).
1610         let mut push_amt = 100_000_000;
1611         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1612         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1613         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1614
1615         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1616                 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1617         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1618         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1619         // commitment transaction fee.
1620         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1621
1622         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1623         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1624                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1625         }
1626
1627         // One more than the dust amt should fail, however.
1628         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1629         unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1630                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1631                 ), true, APIError::ChannelUnavailable { ref err },
1632                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1633 }
1634
1635 #[test]
1636 fn test_chan_init_feerate_unaffordability() {
1637         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1638         // channel reserve and feerate requirements.
1639         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1640         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1641         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1642         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1643         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1644         let default_config = UserConfig::default();
1645         let opt_anchors = false;
1646
1647         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1648         // HTLC.
1649         let mut push_amt = 100_000_000;
1650         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1651         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1652                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1653
1654         // During open, we don't have a "counterparty channel reserve" to check against, so that
1655         // requirement only comes into play on the open_channel handling side.
1656         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1657         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1658         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1659         open_channel_msg.push_msat += 1;
1660         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1661
1662         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1663         assert_eq!(msg_events.len(), 1);
1664         match msg_events[0] {
1665                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1666                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1667                 },
1668                 _ => panic!("Unexpected event"),
1669         }
1670 }
1671
1672 #[test]
1673 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1674         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1675         // calculating our counterparty's commitment transaction fee (this was previously broken).
1676         let chanmon_cfgs = create_chanmon_cfgs(2);
1677         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1678         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1679         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1680         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1681
1682         let payment_amt = 46000; // Dust amount
1683         // In the previous code, these first four payments would succeed.
1684         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1685         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1686         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1687         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1688
1689         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
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         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1695
1696         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1697         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1698         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1699         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1700 }
1701
1702 #[test]
1703 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1704         let chanmon_cfgs = create_chanmon_cfgs(3);
1705         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1706         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1707         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1708         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1709         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1710
1711         let feemsat = 239;
1712         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1713         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1714         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1715         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
1716
1717         // Add a 2* and +1 for the fee spike reserve.
1718         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1719         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;
1720         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1721
1722         // Add a pending HTLC.
1723         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1724         let payment_event_1 = {
1725                 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1726                         RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1727                 check_added_monitors!(nodes[0], 1);
1728
1729                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1730                 assert_eq!(events.len(), 1);
1731                 SendEvent::from_event(events.remove(0))
1732         };
1733         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1734
1735         // Attempt to trigger a channel reserve violation --> payment failure.
1736         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1737         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;
1738         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1739         let mut route_2 = route_1.clone();
1740         route_2.paths[0].hops.last_mut().unwrap().fee_msat = amt_msat_2;
1741
1742         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1743         let secp_ctx = Secp256k1::new();
1744         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1745         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1746         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1747         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
1748                 &route_2.paths[0], recv_value_2, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
1749         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1).unwrap();
1750         let msg = msgs::UpdateAddHTLC {
1751                 channel_id: chan.2,
1752                 htlc_id: 1,
1753                 amount_msat: htlc_msat + 1,
1754                 payment_hash: our_payment_hash_1,
1755                 cltv_expiry: htlc_cltv,
1756                 onion_routing_packet: onion_packet,
1757         };
1758
1759         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1760         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1761         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1762         assert_eq!(nodes[1].node.list_channels().len(), 1);
1763         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1764         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1765         check_added_monitors!(nodes[1], 1);
1766         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1767 }
1768
1769 #[test]
1770 fn test_inbound_outbound_capacity_is_not_zero() {
1771         let chanmon_cfgs = create_chanmon_cfgs(2);
1772         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1773         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1774         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1775         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1776         let channels0 = node_chanmgrs[0].list_channels();
1777         let channels1 = node_chanmgrs[1].list_channels();
1778         let default_config = UserConfig::default();
1779         assert_eq!(channels0.len(), 1);
1780         assert_eq!(channels1.len(), 1);
1781
1782         let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1783         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1784         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1785
1786         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1787         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1788 }
1789
1790 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1791         (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1792 }
1793
1794 #[test]
1795 fn test_channel_reserve_holding_cell_htlcs() {
1796         let chanmon_cfgs = create_chanmon_cfgs(3);
1797         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1798         // When this test was written, the default base fee floated based on the HTLC count.
1799         // It is now fixed, so we simply set the fee to the expected value here.
1800         let mut config = test_default_channel_config();
1801         config.channel_config.forwarding_fee_base_msat = 239;
1802         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1803         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1804         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1805         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1806
1807         let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1808         let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1809
1810         let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1811         let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1812
1813         macro_rules! expect_forward {
1814                 ($node: expr) => {{
1815                         let mut events = $node.node.get_and_clear_pending_msg_events();
1816                         assert_eq!(events.len(), 1);
1817                         check_added_monitors!($node, 1);
1818                         let payment_event = SendEvent::from_event(events.remove(0));
1819                         payment_event
1820                 }}
1821         }
1822
1823         let feemsat = 239; // set above
1824         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1825         let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1826         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_1.2);
1827
1828         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1829
1830         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1831         {
1832                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1833                         .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1834                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0);
1835                 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1836                 assert!(route.paths[0].hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1837
1838                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1839                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1840                         ), true, APIError::ChannelUnavailable { ref err },
1841                         assert!(regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap().is_match(err)));
1842                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1843                 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put us over the max HTLC value in flight our peer will accept", 1);
1844         }
1845
1846         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1847         // nodes[0]'s wealth
1848         loop {
1849                 let amt_msat = recv_value_0 + total_fee_msat;
1850                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1851                 // Also, ensure that each payment has enough to be over the dust limit to
1852                 // ensure it'll be included in each commit tx fee calculation.
1853                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1854                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1855                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1856                         break;
1857                 }
1858
1859                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1860                         .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1861                 let route = get_route!(nodes[0], payment_params, recv_value_0).unwrap();
1862                 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1863                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1864
1865                 let (stat01_, stat11_, stat12_, stat22_) = (
1866                         get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1867                         get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1868                         get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1869                         get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1870                 );
1871
1872                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1873                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1874                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1875                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1876                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1877         }
1878
1879         // adding pending output.
1880         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1881         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1882         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1883         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1884         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1885         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1886         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1887         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1888         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1889         // policy.
1890         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1891         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1892         let amt_msat_1 = recv_value_1 + total_fee_msat;
1893
1894         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);
1895         let payment_event_1 = {
1896                 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1897                         RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1898                 check_added_monitors!(nodes[0], 1);
1899
1900                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1901                 assert_eq!(events.len(), 1);
1902                 SendEvent::from_event(events.remove(0))
1903         };
1904         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1905
1906         // channel reserve test with htlc pending output > 0
1907         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1908         {
1909                 let mut route = route_1.clone();
1910                 route.paths[0].hops.last_mut().unwrap().fee_msat = recv_value_2 + 1;
1911                 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
1912                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1913                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1914                         ), true, APIError::ChannelUnavailable { ref err },
1915                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1916                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1917         }
1918
1919         // split the rest to test holding cell
1920         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1921         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1922         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1923         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1924         {
1925                 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1926                 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);
1927         }
1928
1929         // now see if they go through on both sides
1930         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);
1931         // but this will stuck in the holding cell
1932         nodes[0].node.send_payment_with_route(&route_21, our_payment_hash_21,
1933                 RecipientOnionFields::secret_only(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1934         check_added_monitors!(nodes[0], 0);
1935         let events = nodes[0].node.get_and_clear_pending_events();
1936         assert_eq!(events.len(), 0);
1937
1938         // test with outbound holding cell amount > 0
1939         {
1940                 let (mut route, our_payment_hash, _, our_payment_secret) =
1941                         get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1942                 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1943                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1944                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1945                         ), true, APIError::ChannelUnavailable { ref err },
1946                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1947                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1948                 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put our balance under counterparty-announced channel reserve value", 2);
1949         }
1950
1951         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);
1952         // this will also stuck in the holding cell
1953         nodes[0].node.send_payment_with_route(&route_22, our_payment_hash_22,
1954                 RecipientOnionFields::secret_only(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1955         check_added_monitors!(nodes[0], 0);
1956         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1957         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1958
1959         // flush the pending htlc
1960         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1961         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1962         check_added_monitors!(nodes[1], 1);
1963
1964         // the pending htlc should be promoted to committed
1965         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1966         check_added_monitors!(nodes[0], 1);
1967         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1968
1969         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1970         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1971         // No commitment_signed so get_event_msg's assert(len == 1) passes
1972         check_added_monitors!(nodes[0], 1);
1973
1974         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1975         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1976         check_added_monitors!(nodes[1], 1);
1977
1978         expect_pending_htlcs_forwardable!(nodes[1]);
1979
1980         let ref payment_event_11 = expect_forward!(nodes[1]);
1981         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1982         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1983
1984         expect_pending_htlcs_forwardable!(nodes[2]);
1985         expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1986
1987         // flush the htlcs in the holding cell
1988         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1989         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1990         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1991         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1992         expect_pending_htlcs_forwardable!(nodes[1]);
1993
1994         let ref payment_event_3 = expect_forward!(nodes[1]);
1995         assert_eq!(payment_event_3.msgs.len(), 2);
1996         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1997         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1998
1999         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2000         expect_pending_htlcs_forwardable!(nodes[2]);
2001
2002         let events = nodes[2].node.get_and_clear_pending_events();
2003         assert_eq!(events.len(), 2);
2004         match events[0] {
2005                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2006                         assert_eq!(our_payment_hash_21, *payment_hash);
2007                         assert_eq!(recv_value_21, amount_msat);
2008                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2009                         assert_eq!(via_channel_id, Some(chan_2.2));
2010                         match &purpose {
2011                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2012                                         assert!(payment_preimage.is_none());
2013                                         assert_eq!(our_payment_secret_21, *payment_secret);
2014                                 },
2015                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2016                         }
2017                 },
2018                 _ => panic!("Unexpected event"),
2019         }
2020         match events[1] {
2021                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2022                         assert_eq!(our_payment_hash_22, *payment_hash);
2023                         assert_eq!(recv_value_22, amount_msat);
2024                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2025                         assert_eq!(via_channel_id, Some(chan_2.2));
2026                         match &purpose {
2027                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2028                                         assert!(payment_preimage.is_none());
2029                                         assert_eq!(our_payment_secret_22, *payment_secret);
2030                                 },
2031                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2032                         }
2033                 },
2034                 _ => panic!("Unexpected event"),
2035         }
2036
2037         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2038         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2039         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2040
2041         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2042         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2043         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2044
2045         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2046         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);
2047         let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2048         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2049         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2050
2051         let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2052         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2053 }
2054
2055 #[test]
2056 fn channel_reserve_in_flight_removes() {
2057         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2058         // can send to its counterparty, but due to update ordering, the other side may not yet have
2059         // considered those HTLCs fully removed.
2060         // This tests that we don't count HTLCs which will not be included in the next remote
2061         // commitment transaction towards the reserve value (as it implies no commitment transaction
2062         // will be generated which violates the remote reserve value).
2063         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2064         // To test this we:
2065         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2066         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2067         //    you only consider the value of the first HTLC, it may not),
2068         //  * start routing a third HTLC from A to B,
2069         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2070         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2071         //  * deliver the first fulfill from B
2072         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2073         //    claim,
2074         //  * deliver A's response CS and RAA.
2075         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2076         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2077         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2078         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2079         let chanmon_cfgs = create_chanmon_cfgs(2);
2080         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2081         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2082         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2083         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2084
2085         let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2086         // Route the first two HTLCs.
2087         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2088         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2089         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2090
2091         // Start routing the third HTLC (this is just used to get everyone in the right state).
2092         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2093         let send_1 = {
2094                 nodes[0].node.send_payment_with_route(&route, payment_hash_3,
2095                         RecipientOnionFields::secret_only(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2096                 check_added_monitors!(nodes[0], 1);
2097                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2098                 assert_eq!(events.len(), 1);
2099                 SendEvent::from_event(events.remove(0))
2100         };
2101
2102         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2103         // initial fulfill/CS.
2104         nodes[1].node.claim_funds(payment_preimage_1);
2105         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2106         check_added_monitors!(nodes[1], 1);
2107         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2108
2109         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2110         // remove the second HTLC when we send the HTLC back from B to A.
2111         nodes[1].node.claim_funds(payment_preimage_2);
2112         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2113         check_added_monitors!(nodes[1], 1);
2114         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2115
2116         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2117         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2118         check_added_monitors!(nodes[0], 1);
2119         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2120         expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2121
2122         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2123         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2124         check_added_monitors!(nodes[1], 1);
2125         // B is already AwaitingRAA, so cant generate a CS here
2126         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2127
2128         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2129         check_added_monitors!(nodes[1], 1);
2130         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2131
2132         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2133         check_added_monitors!(nodes[0], 1);
2134         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2135
2136         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2137         check_added_monitors!(nodes[1], 1);
2138         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2139
2140         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2141         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2142         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2143         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2144         // on-chain as necessary).
2145         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2146         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2147         check_added_monitors!(nodes[0], 1);
2148         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2149         expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2150
2151         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2152         check_added_monitors!(nodes[1], 1);
2153         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2154
2155         expect_pending_htlcs_forwardable!(nodes[1]);
2156         expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2157
2158         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2159         // resolve the second HTLC from A's point of view.
2160         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2161         check_added_monitors!(nodes[0], 1);
2162         expect_payment_path_successful!(nodes[0]);
2163         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2164
2165         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2166         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2167         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2168         let send_2 = {
2169                 nodes[1].node.send_payment_with_route(&route, payment_hash_4,
2170                         RecipientOnionFields::secret_only(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2171                 check_added_monitors!(nodes[1], 1);
2172                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2173                 assert_eq!(events.len(), 1);
2174                 SendEvent::from_event(events.remove(0))
2175         };
2176
2177         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2178         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2179         check_added_monitors!(nodes[0], 1);
2180         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2181
2182         // Now just resolve all the outstanding messages/HTLCs for completeness...
2183
2184         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2185         check_added_monitors!(nodes[1], 1);
2186         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2187
2188         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2189         check_added_monitors!(nodes[1], 1);
2190
2191         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2192         check_added_monitors!(nodes[0], 1);
2193         expect_payment_path_successful!(nodes[0]);
2194         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2195
2196         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2197         check_added_monitors!(nodes[1], 1);
2198         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2199
2200         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2201         check_added_monitors!(nodes[0], 1);
2202
2203         expect_pending_htlcs_forwardable!(nodes[0]);
2204         expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2205
2206         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2207         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2208 }
2209
2210 #[test]
2211 fn channel_monitor_network_test() {
2212         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2213         // tests that ChannelMonitor is able to recover from various states.
2214         let chanmon_cfgs = create_chanmon_cfgs(5);
2215         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2216         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2217         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2218
2219         // Create some initial channels
2220         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2221         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2222         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2223         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2224
2225         // Make sure all nodes are at the same starting height
2226         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2227         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2228         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2229         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2230         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2231
2232         // Rebalance the network a bit by relaying one payment through all the channels...
2233         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2234         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2235         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2236         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2237
2238         // Simple case with no pending HTLCs:
2239         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2240         check_added_monitors!(nodes[1], 1);
2241         check_closed_broadcast!(nodes[1], true);
2242         {
2243                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2244                 assert_eq!(node_txn.len(), 1);
2245                 mine_transaction(&nodes[0], &node_txn[0]);
2246                 check_added_monitors!(nodes[0], 1);
2247                 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2248         }
2249         check_closed_broadcast!(nodes[0], true);
2250         assert_eq!(nodes[0].node.list_channels().len(), 0);
2251         assert_eq!(nodes[1].node.list_channels().len(), 1);
2252         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2253         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2254
2255         // One pending HTLC is discarded by the force-close:
2256         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2257
2258         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2259         // broadcasted until we reach the timelock time).
2260         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2261         check_closed_broadcast!(nodes[1], true);
2262         check_added_monitors!(nodes[1], 1);
2263         {
2264                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2265                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2266                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2267                 mine_transaction(&nodes[2], &node_txn[0]);
2268                 check_added_monitors!(nodes[2], 1);
2269                 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2270         }
2271         check_closed_broadcast!(nodes[2], true);
2272         assert_eq!(nodes[1].node.list_channels().len(), 0);
2273         assert_eq!(nodes[2].node.list_channels().len(), 1);
2274         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2275         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2276
2277         macro_rules! claim_funds {
2278                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2279                         {
2280                                 $node.node.claim_funds($preimage);
2281                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2282                                 check_added_monitors!($node, 1);
2283
2284                                 let events = $node.node.get_and_clear_pending_msg_events();
2285                                 assert_eq!(events.len(), 1);
2286                                 match events[0] {
2287                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2288                                                 assert!(update_add_htlcs.is_empty());
2289                                                 assert!(update_fail_htlcs.is_empty());
2290                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2291                                         },
2292                                         _ => panic!("Unexpected event"),
2293                                 };
2294                         }
2295                 }
2296         }
2297
2298         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2299         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2300         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2301         check_added_monitors!(nodes[2], 1);
2302         check_closed_broadcast!(nodes[2], true);
2303         let node2_commitment_txid;
2304         {
2305                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2306                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2307                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2308                 node2_commitment_txid = node_txn[0].txid();
2309
2310                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2311                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2312                 mine_transaction(&nodes[3], &node_txn[0]);
2313                 check_added_monitors!(nodes[3], 1);
2314                 check_preimage_claim(&nodes[3], &node_txn);
2315         }
2316         check_closed_broadcast!(nodes[3], true);
2317         assert_eq!(nodes[2].node.list_channels().len(), 0);
2318         assert_eq!(nodes[3].node.list_channels().len(), 1);
2319         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2320         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2321
2322         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2323         // confusing us in the following tests.
2324         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2325
2326         // One pending HTLC to time out:
2327         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2328         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2329         // buffer space).
2330
2331         let (close_chan_update_1, close_chan_update_2) = {
2332                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2333                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2334                 assert_eq!(events.len(), 2);
2335                 let close_chan_update_1 = match events[0] {
2336                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2337                                 msg.clone()
2338                         },
2339                         _ => panic!("Unexpected event"),
2340                 };
2341                 match events[1] {
2342                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2343                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2344                         },
2345                         _ => panic!("Unexpected event"),
2346                 }
2347                 check_added_monitors!(nodes[3], 1);
2348
2349                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2350                 {
2351                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2352                         node_txn.retain(|tx| {
2353                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2354                                         false
2355                                 } else { true }
2356                         });
2357                 }
2358
2359                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2360
2361                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2362                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2363
2364                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2365                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2366                 assert_eq!(events.len(), 2);
2367                 let close_chan_update_2 = match events[0] {
2368                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2369                                 msg.clone()
2370                         },
2371                         _ => panic!("Unexpected event"),
2372                 };
2373                 match events[1] {
2374                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2375                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2376                         },
2377                         _ => panic!("Unexpected event"),
2378                 }
2379                 check_added_monitors!(nodes[4], 1);
2380                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2381
2382                 mine_transaction(&nodes[4], &node_txn[0]);
2383                 check_preimage_claim(&nodes[4], &node_txn);
2384                 (close_chan_update_1, close_chan_update_2)
2385         };
2386         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2387         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2388         assert_eq!(nodes[3].node.list_channels().len(), 0);
2389         assert_eq!(nodes[4].node.list_channels().len(), 0);
2390
2391         assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2392                 ChannelMonitorUpdateStatus::Completed);
2393         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2394         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2395 }
2396
2397 #[test]
2398 fn test_justice_tx_htlc_timeout() {
2399         // Test justice txn built on revoked HTLC-Timeout tx, against both sides
2400         let mut alice_config = UserConfig::default();
2401         alice_config.channel_handshake_config.announced_channel = true;
2402         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2403         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2404         let mut bob_config = UserConfig::default();
2405         bob_config.channel_handshake_config.announced_channel = true;
2406         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2407         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2408         let user_cfgs = [Some(alice_config), Some(bob_config)];
2409         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2410         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2411         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2412         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2413         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2414         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2415         // Create some new channels:
2416         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2417
2418         // A pending HTLC which will be revoked:
2419         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2420         // Get the will-be-revoked local txn from nodes[0]
2421         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2422         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2423         assert_eq!(revoked_local_txn[0].input.len(), 1);
2424         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2425         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2426         assert_eq!(revoked_local_txn[1].input.len(), 1);
2427         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2428         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2429         // Revoke the old state
2430         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2431
2432         {
2433                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2434                 {
2435                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2436                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2437                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2438                         check_spends!(node_txn[0], revoked_local_txn[0]);
2439                         node_txn.swap_remove(0);
2440                 }
2441                 check_added_monitors!(nodes[1], 1);
2442                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2443                 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2444
2445                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2446                 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2447                 // Verify broadcast of revoked HTLC-timeout
2448                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2449                 check_added_monitors!(nodes[0], 1);
2450                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2451                 // Broadcast revoked HTLC-timeout on node 1
2452                 mine_transaction(&nodes[1], &node_txn[1]);
2453                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2454         }
2455         get_announce_close_broadcast_events(&nodes, 0, 1);
2456         assert_eq!(nodes[0].node.list_channels().len(), 0);
2457         assert_eq!(nodes[1].node.list_channels().len(), 0);
2458 }
2459
2460 #[test]
2461 fn test_justice_tx_htlc_success() {
2462         // Test justice txn built on revoked HTLC-Success tx, against both sides
2463         let mut alice_config = UserConfig::default();
2464         alice_config.channel_handshake_config.announced_channel = true;
2465         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2466         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2467         let mut bob_config = UserConfig::default();
2468         bob_config.channel_handshake_config.announced_channel = true;
2469         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2470         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2471         let user_cfgs = [Some(alice_config), Some(bob_config)];
2472         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2473         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2474         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2475         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2476         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2477         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2478         // Create some new channels:
2479         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2480
2481         // A pending HTLC which will be revoked:
2482         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2483         // Get the will-be-revoked local txn from B
2484         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2485         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2486         assert_eq!(revoked_local_txn[0].input.len(), 1);
2487         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2488         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2489         // Revoke the old state
2490         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2491         {
2492                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2493                 {
2494                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2495                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2496                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2497
2498                         check_spends!(node_txn[0], revoked_local_txn[0]);
2499                         node_txn.swap_remove(0);
2500                 }
2501                 check_added_monitors!(nodes[0], 1);
2502                 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2503
2504                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2505                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2506                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2507                 check_added_monitors!(nodes[1], 1);
2508                 mine_transaction(&nodes[0], &node_txn[1]);
2509                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2510                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2511         }
2512         get_announce_close_broadcast_events(&nodes, 0, 1);
2513         assert_eq!(nodes[0].node.list_channels().len(), 0);
2514         assert_eq!(nodes[1].node.list_channels().len(), 0);
2515 }
2516
2517 #[test]
2518 fn revoked_output_claim() {
2519         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2520         // transaction is broadcast by its counterparty
2521         let chanmon_cfgs = create_chanmon_cfgs(2);
2522         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2523         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2524         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2525         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2526         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2527         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2528         assert_eq!(revoked_local_txn.len(), 1);
2529         // Only output is the full channel value back to nodes[0]:
2530         assert_eq!(revoked_local_txn[0].output.len(), 1);
2531         // Send a payment through, updating everyone's latest commitment txn
2532         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2533
2534         // Inform nodes[1] that nodes[0] broadcast a stale tx
2535         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2536         check_added_monitors!(nodes[1], 1);
2537         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2538         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2539         assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2540
2541         check_spends!(node_txn[0], revoked_local_txn[0]);
2542
2543         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2544         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2545         get_announce_close_broadcast_events(&nodes, 0, 1);
2546         check_added_monitors!(nodes[0], 1);
2547         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2548 }
2549
2550 #[test]
2551 fn claim_htlc_outputs_shared_tx() {
2552         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2553         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2554         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2555         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2556         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2557         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2558
2559         // Create some new channel:
2560         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2561
2562         // Rebalance the network to generate htlc in the two directions
2563         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2564         // 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
2565         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2566         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2567
2568         // Get the will-be-revoked local txn from node[0]
2569         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2570         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2571         assert_eq!(revoked_local_txn[0].input.len(), 1);
2572         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2573         assert_eq!(revoked_local_txn[1].input.len(), 1);
2574         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2575         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2576         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2577
2578         //Revoke the old state
2579         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2580
2581         {
2582                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2583                 check_added_monitors!(nodes[0], 1);
2584                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2585                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2586                 check_added_monitors!(nodes[1], 1);
2587                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2588                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2589                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2590
2591                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2592                 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2593
2594                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2595                 check_spends!(node_txn[0], revoked_local_txn[0]);
2596
2597                 let mut witness_lens = BTreeSet::new();
2598                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2599                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2600                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2601                 assert_eq!(witness_lens.len(), 3);
2602                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2603                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2604                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2605
2606                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2607                 // ANTI_REORG_DELAY confirmations.
2608                 mine_transaction(&nodes[1], &node_txn[0]);
2609                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2610                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2611         }
2612         get_announce_close_broadcast_events(&nodes, 0, 1);
2613         assert_eq!(nodes[0].node.list_channels().len(), 0);
2614         assert_eq!(nodes[1].node.list_channels().len(), 0);
2615 }
2616
2617 #[test]
2618 fn claim_htlc_outputs_single_tx() {
2619         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2620         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2621         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2622         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2623         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2624         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2625
2626         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2627
2628         // Rebalance the network to generate htlc in the two directions
2629         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2630         // 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
2631         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2632         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2633         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2634
2635         // Get the will-be-revoked local txn from node[0]
2636         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2637
2638         //Revoke the old state
2639         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2640
2641         {
2642                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2643                 check_added_monitors!(nodes[0], 1);
2644                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2645                 check_added_monitors!(nodes[1], 1);
2646                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2647                 let mut events = nodes[0].node.get_and_clear_pending_events();
2648                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2649                 match events.last().unwrap() {
2650                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2651                         _ => panic!("Unexpected event"),
2652                 }
2653
2654                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2655                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2656
2657                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcast();
2658
2659                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2660                 assert_eq!(node_txn[0].input.len(), 1);
2661                 check_spends!(node_txn[0], chan_1.3);
2662                 assert_eq!(node_txn[1].input.len(), 1);
2663                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2664                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2665                 check_spends!(node_txn[1], node_txn[0]);
2666
2667                 // Filter out any non justice transactions.
2668                 node_txn.retain(|tx| tx.input[0].previous_output.txid == revoked_local_txn[0].txid());
2669                 assert!(node_txn.len() > 3);
2670
2671                 assert_eq!(node_txn[0].input.len(), 1);
2672                 assert_eq!(node_txn[1].input.len(), 1);
2673                 assert_eq!(node_txn[2].input.len(), 1);
2674
2675                 check_spends!(node_txn[0], revoked_local_txn[0]);
2676                 check_spends!(node_txn[1], revoked_local_txn[0]);
2677                 check_spends!(node_txn[2], revoked_local_txn[0]);
2678
2679                 let mut witness_lens = BTreeSet::new();
2680                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2681                 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2682                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2683                 assert_eq!(witness_lens.len(), 3);
2684                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2685                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2686                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2687
2688                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2689                 // ANTI_REORG_DELAY confirmations.
2690                 mine_transaction(&nodes[1], &node_txn[0]);
2691                 mine_transaction(&nodes[1], &node_txn[1]);
2692                 mine_transaction(&nodes[1], &node_txn[2]);
2693                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2694                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2695         }
2696         get_announce_close_broadcast_events(&nodes, 0, 1);
2697         assert_eq!(nodes[0].node.list_channels().len(), 0);
2698         assert_eq!(nodes[1].node.list_channels().len(), 0);
2699 }
2700
2701 #[test]
2702 fn test_htlc_on_chain_success() {
2703         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2704         // the preimage backward accordingly. So here we test that ChannelManager is
2705         // broadcasting the right event to other nodes in payment path.
2706         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2707         // A --------------------> B ----------------------> C (preimage)
2708         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2709         // commitment transaction was broadcast.
2710         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2711         // towards B.
2712         // B should be able to claim via preimage if A then broadcasts its local tx.
2713         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2714         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2715         // PaymentSent event).
2716
2717         let chanmon_cfgs = create_chanmon_cfgs(3);
2718         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2719         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2720         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2721
2722         // Create some initial channels
2723         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2724         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2725
2726         // Ensure all nodes are at the same height
2727         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2728         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2729         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2730         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2731
2732         // Rebalance the network a bit by relaying one payment through all the channels...
2733         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2734         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2735
2736         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2737         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2738
2739         // Broadcast legit commitment tx from C on B's chain
2740         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2741         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2742         assert_eq!(commitment_tx.len(), 1);
2743         check_spends!(commitment_tx[0], chan_2.3);
2744         nodes[2].node.claim_funds(our_payment_preimage);
2745         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2746         nodes[2].node.claim_funds(our_payment_preimage_2);
2747         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2748         check_added_monitors!(nodes[2], 2);
2749         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2750         assert!(updates.update_add_htlcs.is_empty());
2751         assert!(updates.update_fail_htlcs.is_empty());
2752         assert!(updates.update_fail_malformed_htlcs.is_empty());
2753         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2754
2755         mine_transaction(&nodes[2], &commitment_tx[0]);
2756         check_closed_broadcast!(nodes[2], true);
2757         check_added_monitors!(nodes[2], 1);
2758         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2759         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2760         assert_eq!(node_txn.len(), 2);
2761         check_spends!(node_txn[0], commitment_tx[0]);
2762         check_spends!(node_txn[1], commitment_tx[0]);
2763         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2764         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2765         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2766         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2767         assert_eq!(node_txn[0].lock_time.0, 0);
2768         assert_eq!(node_txn[1].lock_time.0, 0);
2769
2770         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2771         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()]));
2772         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2773         {
2774                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2775                 assert_eq!(added_monitors.len(), 1);
2776                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2777                 added_monitors.clear();
2778         }
2779         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2780         assert_eq!(forwarded_events.len(), 3);
2781         match forwarded_events[0] {
2782                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2783                 _ => panic!("Unexpected event"),
2784         }
2785         let chan_id = Some(chan_1.2);
2786         match forwarded_events[1] {
2787                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2788                         assert_eq!(fee_earned_msat, Some(1000));
2789                         assert_eq!(prev_channel_id, chan_id);
2790                         assert_eq!(claim_from_onchain_tx, true);
2791                         assert_eq!(next_channel_id, Some(chan_2.2));
2792                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2793                 },
2794                 _ => panic!()
2795         }
2796         match forwarded_events[2] {
2797                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2798                         assert_eq!(fee_earned_msat, Some(1000));
2799                         assert_eq!(prev_channel_id, chan_id);
2800                         assert_eq!(claim_from_onchain_tx, true);
2801                         assert_eq!(next_channel_id, Some(chan_2.2));
2802                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2803                 },
2804                 _ => panic!()
2805         }
2806         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2807         {
2808                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2809                 assert_eq!(added_monitors.len(), 2);
2810                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2811                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2812                 added_monitors.clear();
2813         }
2814         assert_eq!(events.len(), 3);
2815
2816         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2817         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2818
2819         match nodes_2_event {
2820                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2821                 _ => panic!("Unexpected event"),
2822         }
2823
2824         match nodes_0_event {
2825                 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, .. } } => {
2826                         assert!(update_add_htlcs.is_empty());
2827                         assert!(update_fail_htlcs.is_empty());
2828                         assert_eq!(update_fulfill_htlcs.len(), 1);
2829                         assert!(update_fail_malformed_htlcs.is_empty());
2830                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2831                 },
2832                 _ => panic!("Unexpected event"),
2833         };
2834
2835         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2836         match events[0] {
2837                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2838                 _ => panic!("Unexpected event"),
2839         }
2840
2841         macro_rules! check_tx_local_broadcast {
2842                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2843                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2844                         assert_eq!(node_txn.len(), 2);
2845                         // Node[1]: 2 * HTLC-timeout tx
2846                         // Node[0]: 2 * HTLC-timeout tx
2847                         check_spends!(node_txn[0], $commitment_tx);
2848                         check_spends!(node_txn[1], $commitment_tx);
2849                         assert_ne!(node_txn[0].lock_time.0, 0);
2850                         assert_ne!(node_txn[1].lock_time.0, 0);
2851                         if $htlc_offered {
2852                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2853                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2854                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2855                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2856                         } else {
2857                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2858                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2859                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2860                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2861                         }
2862                         node_txn.clear();
2863                 } }
2864         }
2865         // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2866         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2867
2868         // Broadcast legit commitment tx from A on B's chain
2869         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2870         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2871         check_spends!(node_a_commitment_tx[0], chan_1.3);
2872         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2873         check_closed_broadcast!(nodes[1], true);
2874         check_added_monitors!(nodes[1], 1);
2875         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2876         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2877         assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2878         let commitment_spend =
2879                 if node_txn.len() == 1 {
2880                         &node_txn[0]
2881                 } else {
2882                         // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2883                         // FullBlockViaListen
2884                         if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2885                                 check_spends!(node_txn[1], commitment_tx[0]);
2886                                 check_spends!(node_txn[2], commitment_tx[0]);
2887                                 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2888                                 &node_txn[0]
2889                         } else {
2890                                 check_spends!(node_txn[0], commitment_tx[0]);
2891                                 check_spends!(node_txn[1], commitment_tx[0]);
2892                                 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2893                                 &node_txn[2]
2894                         }
2895                 };
2896
2897         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2898         assert_eq!(commitment_spend.input.len(), 2);
2899         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2900         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2901         assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1);
2902         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2903         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2904         // we already checked the same situation with A.
2905
2906         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2907         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()]));
2908         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
2909         check_closed_broadcast!(nodes[0], true);
2910         check_added_monitors!(nodes[0], 1);
2911         let events = nodes[0].node.get_and_clear_pending_events();
2912         assert_eq!(events.len(), 5);
2913         let mut first_claimed = false;
2914         for event in events {
2915                 match event {
2916                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2917                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2918                                         assert!(!first_claimed);
2919                                         first_claimed = true;
2920                                 } else {
2921                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2922                                         assert_eq!(payment_hash, payment_hash_2);
2923                                 }
2924                         },
2925                         Event::PaymentPathSuccessful { .. } => {},
2926                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2927                         _ => panic!("Unexpected event"),
2928                 }
2929         }
2930         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
2931 }
2932
2933 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2934         // Test that in case of a unilateral close onchain, we detect the state of output and
2935         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2936         // broadcasting the right event to other nodes in payment path.
2937         // A ------------------> B ----------------------> C (timeout)
2938         //    B's commitment tx                 C's commitment tx
2939         //            \                                  \
2940         //         B's HTLC timeout tx               B's timeout tx
2941
2942         let chanmon_cfgs = create_chanmon_cfgs(3);
2943         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2944         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2945         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2946         *nodes[0].connect_style.borrow_mut() = connect_style;
2947         *nodes[1].connect_style.borrow_mut() = connect_style;
2948         *nodes[2].connect_style.borrow_mut() = connect_style;
2949
2950         // Create some intial channels
2951         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2952         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2953
2954         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2955         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2956         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2957
2958         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2959
2960         // Broadcast legit commitment tx from C on B's chain
2961         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2962         check_spends!(commitment_tx[0], chan_2.3);
2963         nodes[2].node.fail_htlc_backwards(&payment_hash);
2964         check_added_monitors!(nodes[2], 0);
2965         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2966         check_added_monitors!(nodes[2], 1);
2967
2968         let events = nodes[2].node.get_and_clear_pending_msg_events();
2969         assert_eq!(events.len(), 1);
2970         match events[0] {
2971                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
2972                         assert!(update_add_htlcs.is_empty());
2973                         assert!(!update_fail_htlcs.is_empty());
2974                         assert!(update_fulfill_htlcs.is_empty());
2975                         assert!(update_fail_malformed_htlcs.is_empty());
2976                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2977                 },
2978                 _ => panic!("Unexpected event"),
2979         };
2980         mine_transaction(&nodes[2], &commitment_tx[0]);
2981         check_closed_broadcast!(nodes[2], true);
2982         check_added_monitors!(nodes[2], 1);
2983         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2984         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2985         assert_eq!(node_txn.len(), 0);
2986
2987         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2988         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2989         mine_transaction(&nodes[1], &commitment_tx[0]);
2990         check_closed_event(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false);
2991         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2992         let timeout_tx = {
2993                 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
2994                 if nodes[1].connect_style.borrow().skips_blocks() {
2995                         assert_eq!(txn.len(), 1);
2996                 } else {
2997                         assert_eq!(txn.len(), 3); // Two extra fee bumps for timeout transaction
2998                 }
2999                 txn.iter().for_each(|tx| check_spends!(tx, commitment_tx[0]));
3000                 assert_eq!(txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3001                 txn.remove(0)
3002         };
3003
3004         mine_transaction(&nodes[1], &timeout_tx);
3005         check_added_monitors!(nodes[1], 1);
3006         check_closed_broadcast!(nodes[1], true);
3007
3008         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3009
3010         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 }]);
3011         check_added_monitors!(nodes[1], 1);
3012         let events = nodes[1].node.get_and_clear_pending_msg_events();
3013         assert_eq!(events.len(), 1);
3014         match events[0] {
3015                 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, .. } } => {
3016                         assert!(update_add_htlcs.is_empty());
3017                         assert!(!update_fail_htlcs.is_empty());
3018                         assert!(update_fulfill_htlcs.is_empty());
3019                         assert!(update_fail_malformed_htlcs.is_empty());
3020                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3021                 },
3022                 _ => panic!("Unexpected event"),
3023         };
3024
3025         // Broadcast legit commitment tx from B on A's chain
3026         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3027         check_spends!(commitment_tx[0], chan_1.3);
3028
3029         mine_transaction(&nodes[0], &commitment_tx[0]);
3030         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3031
3032         check_closed_broadcast!(nodes[0], true);
3033         check_added_monitors!(nodes[0], 1);
3034         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
3035         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
3036         assert_eq!(node_txn.len(), 1);
3037         check_spends!(node_txn[0], commitment_tx[0]);
3038         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3039 }
3040
3041 #[test]
3042 fn test_htlc_on_chain_timeout() {
3043         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3044         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3045         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3046 }
3047
3048 #[test]
3049 fn test_simple_commitment_revoked_fail_backward() {
3050         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3051         // and fail backward accordingly.
3052
3053         let chanmon_cfgs = create_chanmon_cfgs(3);
3054         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3055         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3056         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3057
3058         // Create some initial channels
3059         create_announced_chan_between_nodes(&nodes, 0, 1);
3060         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3061
3062         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3063         // Get the will-be-revoked local txn from nodes[2]
3064         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3065         // Revoke the old state
3066         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3067
3068         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3069
3070         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3071         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3072         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3073         check_added_monitors!(nodes[1], 1);
3074         check_closed_broadcast!(nodes[1], true);
3075
3076         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 }]);
3077         check_added_monitors!(nodes[1], 1);
3078         let events = nodes[1].node.get_and_clear_pending_msg_events();
3079         assert_eq!(events.len(), 1);
3080         match events[0] {
3081                 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, .. } } => {
3082                         assert!(update_add_htlcs.is_empty());
3083                         assert_eq!(update_fail_htlcs.len(), 1);
3084                         assert!(update_fulfill_htlcs.is_empty());
3085                         assert!(update_fail_malformed_htlcs.is_empty());
3086                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3087
3088                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3089                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3090                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3091                 },
3092                 _ => panic!("Unexpected event"),
3093         }
3094 }
3095
3096 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3097         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3098         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3099         // commitment transaction anymore.
3100         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3101         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3102         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3103         // technically disallowed and we should probably handle it reasonably.
3104         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3105         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3106         // transactions:
3107         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3108         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3109         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3110         //   and once they revoke the previous commitment transaction (allowing us to send a new
3111         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3112         let chanmon_cfgs = create_chanmon_cfgs(3);
3113         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3114         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3115         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3116
3117         // Create some initial channels
3118         create_announced_chan_between_nodes(&nodes, 0, 1);
3119         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3120
3121         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 });
3122         // Get the will-be-revoked local txn from nodes[2]
3123         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3124         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3125         // Revoke the old state
3126         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3127
3128         let value = if use_dust {
3129                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3130                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3131                 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3132                         .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3133         } else { 3000000 };
3134
3135         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3136         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3137         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3138
3139         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3140         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3141         check_added_monitors!(nodes[2], 1);
3142         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3143         assert!(updates.update_add_htlcs.is_empty());
3144         assert!(updates.update_fulfill_htlcs.is_empty());
3145         assert!(updates.update_fail_malformed_htlcs.is_empty());
3146         assert_eq!(updates.update_fail_htlcs.len(), 1);
3147         assert!(updates.update_fee.is_none());
3148         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3149         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3150         // Drop the last RAA from 3 -> 2
3151
3152         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3153         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3154         check_added_monitors!(nodes[2], 1);
3155         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3156         assert!(updates.update_add_htlcs.is_empty());
3157         assert!(updates.update_fulfill_htlcs.is_empty());
3158         assert!(updates.update_fail_malformed_htlcs.is_empty());
3159         assert_eq!(updates.update_fail_htlcs.len(), 1);
3160         assert!(updates.update_fee.is_none());
3161         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3162         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3163         check_added_monitors!(nodes[1], 1);
3164         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3165         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3166         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3167         check_added_monitors!(nodes[2], 1);
3168
3169         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3170         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3171         check_added_monitors!(nodes[2], 1);
3172         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3173         assert!(updates.update_add_htlcs.is_empty());
3174         assert!(updates.update_fulfill_htlcs.is_empty());
3175         assert!(updates.update_fail_malformed_htlcs.is_empty());
3176         assert_eq!(updates.update_fail_htlcs.len(), 1);
3177         assert!(updates.update_fee.is_none());
3178         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3179         // At this point first_payment_hash has dropped out of the latest two commitment
3180         // transactions that nodes[1] is tracking...
3181         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3182         check_added_monitors!(nodes[1], 1);
3183         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3184         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3185         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3186         check_added_monitors!(nodes[2], 1);
3187
3188         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3189         // on nodes[2]'s RAA.
3190         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3191         nodes[1].node.send_payment_with_route(&route, fourth_payment_hash,
3192                 RecipientOnionFields::secret_only(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3193         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3194         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3195         check_added_monitors!(nodes[1], 0);
3196
3197         if deliver_bs_raa {
3198                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3199                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3200                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3201                 check_added_monitors!(nodes[1], 1);
3202                 let events = nodes[1].node.get_and_clear_pending_events();
3203                 assert_eq!(events.len(), 2);
3204                 match events[0] {
3205                         Event::PendingHTLCsForwardable { .. } => { },
3206                         _ => panic!("Unexpected event"),
3207                 };
3208                 match events[1] {
3209                         Event::HTLCHandlingFailed { .. } => { },
3210                         _ => panic!("Unexpected event"),
3211                 }
3212                 // Deliberately don't process the pending fail-back so they all fail back at once after
3213                 // block connection just like the !deliver_bs_raa case
3214         }
3215
3216         let mut failed_htlcs = HashSet::new();
3217         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3218
3219         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3220         check_added_monitors!(nodes[1], 1);
3221         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3222
3223         let events = nodes[1].node.get_and_clear_pending_events();
3224         assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3225         match events[0] {
3226                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3227                 _ => panic!("Unexepected event"),
3228         }
3229         match events[1] {
3230                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3231                         assert_eq!(*payment_hash, fourth_payment_hash);
3232                 },
3233                 _ => panic!("Unexpected event"),
3234         }
3235         match events[2] {
3236                 Event::PaymentFailed { ref payment_hash, .. } => {
3237                         assert_eq!(*payment_hash, fourth_payment_hash);
3238                 },
3239                 _ => panic!("Unexpected event"),
3240         }
3241
3242         nodes[1].node.process_pending_htlc_forwards();
3243         check_added_monitors!(nodes[1], 1);
3244
3245         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3246         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3247
3248         if deliver_bs_raa {
3249                 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3250                 match nodes_2_event {
3251                         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, .. } } => {
3252                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3253                                 assert_eq!(update_add_htlcs.len(), 1);
3254                                 assert!(update_fulfill_htlcs.is_empty());
3255                                 assert!(update_fail_htlcs.is_empty());
3256                                 assert!(update_fail_malformed_htlcs.is_empty());
3257                         },
3258                         _ => panic!("Unexpected event"),
3259                 }
3260         }
3261
3262         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3263         match nodes_2_event {
3264                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3265                         assert_eq!(channel_id, chan_2.2);
3266                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3267                 },
3268                 _ => panic!("Unexpected event"),
3269         }
3270
3271         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3272         match nodes_0_event {
3273                 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, .. } } => {
3274                         assert!(update_add_htlcs.is_empty());
3275                         assert_eq!(update_fail_htlcs.len(), 3);
3276                         assert!(update_fulfill_htlcs.is_empty());
3277                         assert!(update_fail_malformed_htlcs.is_empty());
3278                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3279
3280                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3281                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3282                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3283
3284                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3285
3286                         let events = nodes[0].node.get_and_clear_pending_events();
3287                         assert_eq!(events.len(), 6);
3288                         match events[0] {
3289                                 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3290                                         assert!(failed_htlcs.insert(payment_hash.0));
3291                                         // If we delivered B's RAA we got an unknown preimage error, not something
3292                                         // that we should update our routing table for.
3293                                         if !deliver_bs_raa {
3294                                                 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3295                                         }
3296                                 },
3297                                 _ => panic!("Unexpected event"),
3298                         }
3299                         match events[1] {
3300                                 Event::PaymentFailed { ref payment_hash, .. } => {
3301                                         assert_eq!(*payment_hash, first_payment_hash);
3302                                 },
3303                                 _ => panic!("Unexpected event"),
3304                         }
3305                         match events[2] {
3306                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3307                                         assert!(failed_htlcs.insert(payment_hash.0));
3308                                 },
3309                                 _ => panic!("Unexpected event"),
3310                         }
3311                         match events[3] {
3312                                 Event::PaymentFailed { ref payment_hash, .. } => {
3313                                         assert_eq!(*payment_hash, second_payment_hash);
3314                                 },
3315                                 _ => panic!("Unexpected event"),
3316                         }
3317                         match events[4] {
3318                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3319                                         assert!(failed_htlcs.insert(payment_hash.0));
3320                                 },
3321                                 _ => panic!("Unexpected event"),
3322                         }
3323                         match events[5] {
3324                                 Event::PaymentFailed { ref payment_hash, .. } => {
3325                                         assert_eq!(*payment_hash, third_payment_hash);
3326                                 },
3327                                 _ => panic!("Unexpected event"),
3328                         }
3329                 },
3330                 _ => panic!("Unexpected event"),
3331         }
3332
3333         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3334         match events[0] {
3335                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3336                 _ => panic!("Unexpected event"),
3337         }
3338
3339         assert!(failed_htlcs.contains(&first_payment_hash.0));
3340         assert!(failed_htlcs.contains(&second_payment_hash.0));
3341         assert!(failed_htlcs.contains(&third_payment_hash.0));
3342 }
3343
3344 #[test]
3345 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3346         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3347         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3348         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3349         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3350 }
3351
3352 #[test]
3353 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3354         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3355         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3356         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3357         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3358 }
3359
3360 #[test]
3361 fn fail_backward_pending_htlc_upon_channel_failure() {
3362         let chanmon_cfgs = create_chanmon_cfgs(2);
3363         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3364         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3365         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3366         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3367
3368         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3369         {
3370                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3371                 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret),
3372                         PaymentId(payment_hash.0)).unwrap();
3373                 check_added_monitors!(nodes[0], 1);
3374
3375                 let payment_event = {
3376                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3377                         assert_eq!(events.len(), 1);
3378                         SendEvent::from_event(events.remove(0))
3379                 };
3380                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3381                 assert_eq!(payment_event.msgs.len(), 1);
3382         }
3383
3384         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3385         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3386         {
3387                 nodes[0].node.send_payment_with_route(&route, failed_payment_hash,
3388                         RecipientOnionFields::secret_only(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3389                 check_added_monitors!(nodes[0], 0);
3390
3391                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3392         }
3393
3394         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3395         {
3396                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3397
3398                 let secp_ctx = Secp256k1::new();
3399                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3400                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3401                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(
3402                         &route.paths[0], 50_000, RecipientOnionFields::secret_only(payment_secret), current_height, &None).unwrap();
3403                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3404                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
3405
3406                 // Send a 0-msat update_add_htlc to fail the channel.
3407                 let update_add_htlc = msgs::UpdateAddHTLC {
3408                         channel_id: chan.2,
3409                         htlc_id: 0,
3410                         amount_msat: 0,
3411                         payment_hash,
3412                         cltv_expiry,
3413                         onion_routing_packet,
3414                 };
3415                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3416         }
3417         let events = nodes[0].node.get_and_clear_pending_events();
3418         assert_eq!(events.len(), 3);
3419         // Check that Alice fails backward the pending HTLC from the second payment.
3420         match events[0] {
3421                 Event::PaymentPathFailed { payment_hash, .. } => {
3422                         assert_eq!(payment_hash, failed_payment_hash);
3423                 },
3424                 _ => panic!("Unexpected event"),
3425         }
3426         match events[1] {
3427                 Event::PaymentFailed { payment_hash, .. } => {
3428                         assert_eq!(payment_hash, failed_payment_hash);
3429                 },
3430                 _ => panic!("Unexpected event"),
3431         }
3432         match events[2] {
3433                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3434                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3435                 },
3436                 _ => panic!("Unexpected event {:?}", events[1]),
3437         }
3438         check_closed_broadcast!(nodes[0], true);
3439         check_added_monitors!(nodes[0], 1);
3440 }
3441
3442 #[test]
3443 fn test_htlc_ignore_latest_remote_commitment() {
3444         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3445         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3446         let chanmon_cfgs = create_chanmon_cfgs(2);
3447         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3448         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3449         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3450         if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3451                 // We rely on the ability to connect a block redundantly, which isn't allowed via
3452                 // `chain::Listen`, so we never run the test if we randomly get assigned that
3453                 // connect_style.
3454                 return;
3455         }
3456         create_announced_chan_between_nodes(&nodes, 0, 1);
3457
3458         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3459         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3460         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3461         check_closed_broadcast!(nodes[0], true);
3462         check_added_monitors!(nodes[0], 1);
3463         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3464
3465         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3466         assert_eq!(node_txn.len(), 3);
3467         assert_eq!(node_txn[0].txid(), node_txn[1].txid());
3468
3469         let block = create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[0].clone(), node_txn[1].clone()]);
3470         connect_block(&nodes[1], &block);
3471         check_closed_broadcast!(nodes[1], true);
3472         check_added_monitors!(nodes[1], 1);
3473         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3474
3475         // Duplicate the connect_block call since this may happen due to other listeners
3476         // registering new transactions
3477         connect_block(&nodes[1], &block);
3478 }
3479
3480 #[test]
3481 fn test_force_close_fail_back() {
3482         // Check which HTLCs are failed-backwards on channel force-closure
3483         let chanmon_cfgs = create_chanmon_cfgs(3);
3484         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3485         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3486         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3487         create_announced_chan_between_nodes(&nodes, 0, 1);
3488         create_announced_chan_between_nodes(&nodes, 1, 2);
3489
3490         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3491
3492         let mut payment_event = {
3493                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3494                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3495                 check_added_monitors!(nodes[0], 1);
3496
3497                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3498                 assert_eq!(events.len(), 1);
3499                 SendEvent::from_event(events.remove(0))
3500         };
3501
3502         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3503         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3504
3505         expect_pending_htlcs_forwardable!(nodes[1]);
3506
3507         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3508         assert_eq!(events_2.len(), 1);
3509         payment_event = SendEvent::from_event(events_2.remove(0));
3510         assert_eq!(payment_event.msgs.len(), 1);
3511
3512         check_added_monitors!(nodes[1], 1);
3513         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3514         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3515         check_added_monitors!(nodes[2], 1);
3516         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3517
3518         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3519         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3520         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3521
3522         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3523         check_closed_broadcast!(nodes[2], true);
3524         check_added_monitors!(nodes[2], 1);
3525         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3526         let tx = {
3527                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3528                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3529                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3530                 // back to nodes[1] upon timeout otherwise.
3531                 assert_eq!(node_txn.len(), 1);
3532                 node_txn.remove(0)
3533         };
3534
3535         mine_transaction(&nodes[1], &tx);
3536
3537         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3538         check_closed_broadcast!(nodes[1], true);
3539         check_added_monitors!(nodes[1], 1);
3540         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3541
3542         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3543         {
3544                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3545                         .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);
3546         }
3547         mine_transaction(&nodes[2], &tx);
3548         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3549         assert_eq!(node_txn.len(), 1);
3550         assert_eq!(node_txn[0].input.len(), 1);
3551         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3552         assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3553         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3554
3555         check_spends!(node_txn[0], tx);
3556 }
3557
3558 #[test]
3559 fn test_dup_events_on_peer_disconnect() {
3560         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3561         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3562         // as we used to generate the event immediately upon receipt of the payment preimage in the
3563         // update_fulfill_htlc message.
3564
3565         let chanmon_cfgs = create_chanmon_cfgs(2);
3566         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3567         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3568         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3569         create_announced_chan_between_nodes(&nodes, 0, 1);
3570
3571         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3572
3573         nodes[1].node.claim_funds(payment_preimage);
3574         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3575         check_added_monitors!(nodes[1], 1);
3576         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3577         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3578         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3579
3580         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3581         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3582
3583         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3584         expect_payment_path_successful!(nodes[0]);
3585 }
3586
3587 #[test]
3588 fn test_peer_disconnected_before_funding_broadcasted() {
3589         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3590         // before the funding transaction has been broadcasted.
3591         let chanmon_cfgs = create_chanmon_cfgs(2);
3592         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3593         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3594         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3595
3596         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3597         // broadcasted, even though it's created by `nodes[0]`.
3598         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();
3599         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3600         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3601         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3602         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3603
3604         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3605         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3606
3607         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3608
3609         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3610         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3611
3612         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3613         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3614         // broadcasted.
3615         {
3616                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3617         }
3618
3619         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3620         // disconnected before the funding transaction was broadcasted.
3621         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3622         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3623
3624         check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3625         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3626 }
3627
3628 #[test]
3629 fn test_simple_peer_disconnect() {
3630         // Test that we can reconnect when there are no lost messages
3631         let chanmon_cfgs = create_chanmon_cfgs(3);
3632         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3633         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3634         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3635         create_announced_chan_between_nodes(&nodes, 0, 1);
3636         create_announced_chan_between_nodes(&nodes, 1, 2);
3637
3638         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3639         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3640         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3641
3642         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3643         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3644         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3645         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3646
3647         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3648         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3649         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3650
3651         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3652         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3653         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3654         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3655
3656         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3657         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3658
3659         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3660         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3661
3662         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3663         {
3664                 let events = nodes[0].node.get_and_clear_pending_events();
3665                 assert_eq!(events.len(), 4);
3666                 match events[0] {
3667                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3668                                 assert_eq!(payment_preimage, payment_preimage_3);
3669                                 assert_eq!(payment_hash, payment_hash_3);
3670                         },
3671                         _ => panic!("Unexpected event"),
3672                 }
3673                 match events[1] {
3674                         Event::PaymentPathSuccessful { .. } => {},
3675                         _ => panic!("Unexpected event"),
3676                 }
3677                 match events[2] {
3678                         Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3679                                 assert_eq!(payment_hash, payment_hash_5);
3680                                 assert!(payment_failed_permanently);
3681                         },
3682                         _ => panic!("Unexpected event"),
3683                 }
3684                 match events[3] {
3685                         Event::PaymentFailed { payment_hash, .. } => {
3686                                 assert_eq!(payment_hash, payment_hash_5);
3687                         },
3688                         _ => panic!("Unexpected event"),
3689                 }
3690         }
3691
3692         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3693         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3694 }
3695
3696 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3697         // Test that we can reconnect when in-flight HTLC updates get dropped
3698         let chanmon_cfgs = create_chanmon_cfgs(2);
3699         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3700         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3701         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3702
3703         let mut as_channel_ready = None;
3704         let channel_id = if messages_delivered == 0 {
3705                 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3706                 as_channel_ready = Some(channel_ready);
3707                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3708                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3709                 // it before the channel_reestablish message.
3710                 chan_id
3711         } else {
3712                 create_announced_chan_between_nodes(&nodes, 0, 1).2
3713         };
3714
3715         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3716
3717         let payment_event = {
3718                 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3719                         RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3720                 check_added_monitors!(nodes[0], 1);
3721
3722                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3723                 assert_eq!(events.len(), 1);
3724                 SendEvent::from_event(events.remove(0))
3725         };
3726         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3727
3728         if messages_delivered < 2 {
3729                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3730         } else {
3731                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3732                 if messages_delivered >= 3 {
3733                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3734                         check_added_monitors!(nodes[1], 1);
3735                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3736
3737                         if messages_delivered >= 4 {
3738                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3739                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3740                                 check_added_monitors!(nodes[0], 1);
3741
3742                                 if messages_delivered >= 5 {
3743                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3744                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3745                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3746                                         check_added_monitors!(nodes[0], 1);
3747
3748                                         if messages_delivered >= 6 {
3749                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3750                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3751                                                 check_added_monitors!(nodes[1], 1);
3752                                         }
3753                                 }
3754                         }
3755                 }
3756         }
3757
3758         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3759         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3760         if messages_delivered < 3 {
3761                 if simulate_broken_lnd {
3762                         // lnd has a long-standing bug where they send a channel_ready prior to a
3763                         // channel_reestablish if you reconnect prior to channel_ready time.
3764                         //
3765                         // Here we simulate that behavior, delivering a channel_ready immediately on
3766                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3767                         // in `reconnect_nodes` but we currently don't fail based on that.
3768                         //
3769                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3770                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3771                 }
3772                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3773                 // received on either side, both sides will need to resend them.
3774                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3775         } else if messages_delivered == 3 {
3776                 // nodes[0] still wants its RAA + commitment_signed
3777                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3778         } else if messages_delivered == 4 {
3779                 // nodes[0] still wants its commitment_signed
3780                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3781         } else if messages_delivered == 5 {
3782                 // nodes[1] still wants its final RAA
3783                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3784         } else if messages_delivered == 6 {
3785                 // Everything was delivered...
3786                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3787         }
3788
3789         let events_1 = nodes[1].node.get_and_clear_pending_events();
3790         if messages_delivered == 0 {
3791                 assert_eq!(events_1.len(), 2);
3792                 match events_1[0] {
3793                         Event::ChannelReady { .. } => { },
3794                         _ => panic!("Unexpected event"),
3795                 };
3796                 match events_1[1] {
3797                         Event::PendingHTLCsForwardable { .. } => { },
3798                         _ => panic!("Unexpected event"),
3799                 };
3800         } else {
3801                 assert_eq!(events_1.len(), 1);
3802                 match events_1[0] {
3803                         Event::PendingHTLCsForwardable { .. } => { },
3804                         _ => panic!("Unexpected event"),
3805                 };
3806         }
3807
3808         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3809         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3810         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3811
3812         nodes[1].node.process_pending_htlc_forwards();
3813
3814         let events_2 = nodes[1].node.get_and_clear_pending_events();
3815         assert_eq!(events_2.len(), 1);
3816         match events_2[0] {
3817                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3818                         assert_eq!(payment_hash_1, *payment_hash);
3819                         assert_eq!(amount_msat, 1_000_000);
3820                         assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3821                         assert_eq!(via_channel_id, Some(channel_id));
3822                         match &purpose {
3823                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3824                                         assert!(payment_preimage.is_none());
3825                                         assert_eq!(payment_secret_1, *payment_secret);
3826                                 },
3827                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3828                         }
3829                 },
3830                 _ => panic!("Unexpected event"),
3831         }
3832
3833         nodes[1].node.claim_funds(payment_preimage_1);
3834         check_added_monitors!(nodes[1], 1);
3835         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3836
3837         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3838         assert_eq!(events_3.len(), 1);
3839         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3840                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3841                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3842                         assert!(updates.update_add_htlcs.is_empty());
3843                         assert!(updates.update_fail_htlcs.is_empty());
3844                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3845                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3846                         assert!(updates.update_fee.is_none());
3847                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3848                 },
3849                 _ => panic!("Unexpected event"),
3850         };
3851
3852         if messages_delivered >= 1 {
3853                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3854
3855                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3856                 assert_eq!(events_4.len(), 1);
3857                 match events_4[0] {
3858                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3859                                 assert_eq!(payment_preimage_1, *payment_preimage);
3860                                 assert_eq!(payment_hash_1, *payment_hash);
3861                         },
3862                         _ => panic!("Unexpected event"),
3863                 }
3864
3865                 if messages_delivered >= 2 {
3866                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3867                         check_added_monitors!(nodes[0], 1);
3868                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3869
3870                         if messages_delivered >= 3 {
3871                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3872                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3873                                 check_added_monitors!(nodes[1], 1);
3874
3875                                 if messages_delivered >= 4 {
3876                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3877                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3878                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3879                                         check_added_monitors!(nodes[1], 1);
3880
3881                                         if messages_delivered >= 5 {
3882                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3883                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3884                                                 check_added_monitors!(nodes[0], 1);
3885                                         }
3886                                 }
3887                         }
3888                 }
3889         }
3890
3891         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3892         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3893         if messages_delivered < 2 {
3894                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3895                 if messages_delivered < 1 {
3896                         expect_payment_sent!(nodes[0], payment_preimage_1);
3897                 } else {
3898                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3899                 }
3900         } else if messages_delivered == 2 {
3901                 // nodes[0] still wants its RAA + commitment_signed
3902                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3903         } else if messages_delivered == 3 {
3904                 // nodes[0] still wants its commitment_signed
3905                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3906         } else if messages_delivered == 4 {
3907                 // nodes[1] still wants its final RAA
3908                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3909         } else if messages_delivered == 5 {
3910                 // Everything was delivered...
3911                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3912         }
3913
3914         if messages_delivered == 1 || messages_delivered == 2 {
3915                 expect_payment_path_successful!(nodes[0]);
3916         }
3917         if messages_delivered <= 5 {
3918                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3919                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3920         }
3921         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3922
3923         if messages_delivered > 2 {
3924                 expect_payment_path_successful!(nodes[0]);
3925         }
3926
3927         // Channel should still work fine...
3928         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3929         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3930         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3931 }
3932
3933 #[test]
3934 fn test_drop_messages_peer_disconnect_a() {
3935         do_test_drop_messages_peer_disconnect(0, true);
3936         do_test_drop_messages_peer_disconnect(0, false);
3937         do_test_drop_messages_peer_disconnect(1, false);
3938         do_test_drop_messages_peer_disconnect(2, false);
3939 }
3940
3941 #[test]
3942 fn test_drop_messages_peer_disconnect_b() {
3943         do_test_drop_messages_peer_disconnect(3, false);
3944         do_test_drop_messages_peer_disconnect(4, false);
3945         do_test_drop_messages_peer_disconnect(5, false);
3946         do_test_drop_messages_peer_disconnect(6, false);
3947 }
3948
3949 #[test]
3950 fn test_channel_ready_without_best_block_updated() {
3951         // Previously, if we were offline when a funding transaction was locked in, and then we came
3952         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3953         // generate a channel_ready until a later best_block_updated. This tests that we generate the
3954         // channel_ready immediately instead.
3955         let chanmon_cfgs = create_chanmon_cfgs(2);
3956         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3957         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3958         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3959         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3960
3961         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
3962
3963         let conf_height = nodes[0].best_block_info().1 + 1;
3964         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3965         let block_txn = [funding_tx];
3966         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3967         let conf_block_header = nodes[0].get_block_header(conf_height);
3968         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3969
3970         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
3971         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
3972         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3973 }
3974
3975 #[test]
3976 fn test_drop_messages_peer_disconnect_dual_htlc() {
3977         // Test that we can handle reconnecting when both sides of a channel have pending
3978         // commitment_updates when we disconnect.
3979         let chanmon_cfgs = create_chanmon_cfgs(2);
3980         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3981         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3982         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3983         create_announced_chan_between_nodes(&nodes, 0, 1);
3984
3985         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3986
3987         // Now try to send a second payment which will fail to send
3988         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3989         nodes[0].node.send_payment_with_route(&route, payment_hash_2,
3990                 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
3991         check_added_monitors!(nodes[0], 1);
3992
3993         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3994         assert_eq!(events_1.len(), 1);
3995         match events_1[0] {
3996                 MessageSendEvent::UpdateHTLCs { .. } => {},
3997                 _ => panic!("Unexpected event"),
3998         }
3999
4000         nodes[1].node.claim_funds(payment_preimage_1);
4001         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4002         check_added_monitors!(nodes[1], 1);
4003
4004         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4005         assert_eq!(events_2.len(), 1);
4006         match events_2[0] {
4007                 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 } } => {
4008                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4009                         assert!(update_add_htlcs.is_empty());
4010                         assert_eq!(update_fulfill_htlcs.len(), 1);
4011                         assert!(update_fail_htlcs.is_empty());
4012                         assert!(update_fail_malformed_htlcs.is_empty());
4013                         assert!(update_fee.is_none());
4014
4015                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4016                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4017                         assert_eq!(events_3.len(), 1);
4018                         match events_3[0] {
4019                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4020                                         assert_eq!(*payment_preimage, payment_preimage_1);
4021                                         assert_eq!(*payment_hash, payment_hash_1);
4022                                 },
4023                                 _ => panic!("Unexpected event"),
4024                         }
4025
4026                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4027                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4028                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4029                         check_added_monitors!(nodes[0], 1);
4030                 },
4031                 _ => panic!("Unexpected event"),
4032         }
4033
4034         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4035         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4036
4037         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }, true).unwrap();
4038         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4039         assert_eq!(reestablish_1.len(), 1);
4040         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }, false).unwrap();
4041         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4042         assert_eq!(reestablish_2.len(), 1);
4043
4044         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4045         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4046         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4047         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4048
4049         assert!(as_resp.0.is_none());
4050         assert!(bs_resp.0.is_none());
4051
4052         assert!(bs_resp.1.is_none());
4053         assert!(bs_resp.2.is_none());
4054
4055         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4056
4057         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4058         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4059         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4060         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4061         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4062         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4063         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4064         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4065         // No commitment_signed so get_event_msg's assert(len == 1) passes
4066         check_added_monitors!(nodes[1], 1);
4067
4068         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4069         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4070         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4071         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4072         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4073         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4074         assert!(bs_second_commitment_signed.update_fee.is_none());
4075         check_added_monitors!(nodes[1], 1);
4076
4077         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4078         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4079         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4080         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4081         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4082         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4083         assert!(as_commitment_signed.update_fee.is_none());
4084         check_added_monitors!(nodes[0], 1);
4085
4086         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4087         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4088         // No commitment_signed so get_event_msg's assert(len == 1) passes
4089         check_added_monitors!(nodes[0], 1);
4090
4091         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4092         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4093         // No commitment_signed so get_event_msg's assert(len == 1) passes
4094         check_added_monitors!(nodes[1], 1);
4095
4096         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4097         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4098         check_added_monitors!(nodes[1], 1);
4099
4100         expect_pending_htlcs_forwardable!(nodes[1]);
4101
4102         let events_5 = nodes[1].node.get_and_clear_pending_events();
4103         assert_eq!(events_5.len(), 1);
4104         match events_5[0] {
4105                 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4106                         assert_eq!(payment_hash_2, *payment_hash);
4107                         match &purpose {
4108                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4109                                         assert!(payment_preimage.is_none());
4110                                         assert_eq!(payment_secret_2, *payment_secret);
4111                                 },
4112                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4113                         }
4114                 },
4115                 _ => panic!("Unexpected event"),
4116         }
4117
4118         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4119         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4120         check_added_monitors!(nodes[0], 1);
4121
4122         expect_payment_path_successful!(nodes[0]);
4123         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4124 }
4125
4126 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4127         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4128         // to avoid our counterparty failing the channel.
4129         let chanmon_cfgs = create_chanmon_cfgs(2);
4130         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4131         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4132         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4133
4134         create_announced_chan_between_nodes(&nodes, 0, 1);
4135
4136         let our_payment_hash = if send_partial_mpp {
4137                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4138                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4139                 // indicates there are more HTLCs coming.
4140                 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.
4141                 let payment_id = PaymentId([42; 32]);
4142                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4143                         RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4144                 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4145                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4146                         &None, session_privs[0]).unwrap();
4147                 check_added_monitors!(nodes[0], 1);
4148                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4149                 assert_eq!(events.len(), 1);
4150                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4151                 // hop should *not* yet generate any PaymentClaimable event(s).
4152                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4153                 our_payment_hash
4154         } else {
4155                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4156         };
4157
4158         let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
4159         connect_block(&nodes[0], &block);
4160         connect_block(&nodes[1], &block);
4161         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4162         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4163                 block.header.prev_blockhash = block.block_hash();
4164                 connect_block(&nodes[0], &block);
4165                 connect_block(&nodes[1], &block);
4166         }
4167
4168         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4169
4170         check_added_monitors!(nodes[1], 1);
4171         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4172         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4173         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4174         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4175         assert!(htlc_timeout_updates.update_fee.is_none());
4176
4177         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4178         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4179         // 100_000 msat as u64, followed by the height at which we failed back above
4180         let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4181         expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4182         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4183 }
4184
4185 #[test]
4186 fn test_htlc_timeout() {
4187         do_test_htlc_timeout(true);
4188         do_test_htlc_timeout(false);
4189 }
4190
4191 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4192         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4193         let chanmon_cfgs = create_chanmon_cfgs(3);
4194         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4195         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4196         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4197         create_announced_chan_between_nodes(&nodes, 0, 1);
4198         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4199
4200         // Make sure all nodes are at the same starting height
4201         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4202         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4203         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4204
4205         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4206         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4207         nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4208                 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4209         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4210         check_added_monitors!(nodes[1], 1);
4211
4212         // Now attempt to route a second payment, which should be placed in the holding cell
4213         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4214         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4215         sending_node.node.send_payment_with_route(&route, second_payment_hash,
4216                 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4217         if forwarded_htlc {
4218                 check_added_monitors!(nodes[0], 1);
4219                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4220                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4221                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4222                 expect_pending_htlcs_forwardable!(nodes[1]);
4223         }
4224         check_added_monitors!(nodes[1], 0);
4225
4226         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4227         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4228         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4229         connect_blocks(&nodes[1], 1);
4230
4231         if forwarded_htlc {
4232                 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 }]);
4233                 check_added_monitors!(nodes[1], 1);
4234                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4235                 assert_eq!(fail_commit.len(), 1);
4236                 match fail_commit[0] {
4237                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4238                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4239                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4240                         },
4241                         _ => unreachable!(),
4242                 }
4243                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4244         } else {
4245                 expect_payment_failed!(nodes[1], second_payment_hash, false);
4246         }
4247 }
4248
4249 #[test]
4250 fn test_holding_cell_htlc_add_timeouts() {
4251         do_test_holding_cell_htlc_add_timeouts(false);
4252         do_test_holding_cell_htlc_add_timeouts(true);
4253 }
4254
4255 macro_rules! check_spendable_outputs {
4256         ($node: expr, $keysinterface: expr) => {
4257                 {
4258                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4259                         let mut txn = Vec::new();
4260                         let mut all_outputs = Vec::new();
4261                         let secp_ctx = Secp256k1::new();
4262                         for event in events.drain(..) {
4263                                 match event {
4264                                         Event::SpendableOutputs { mut outputs } => {
4265                                                 for outp in outputs.drain(..) {
4266                                                         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());
4267                                                         all_outputs.push(outp);
4268                                                 }
4269                                         },
4270                                         _ => panic!("Unexpected event"),
4271                                 };
4272                         }
4273                         if all_outputs.len() > 1 {
4274                                 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) {
4275                                         txn.push(tx);
4276                                 }
4277                         }
4278                         txn
4279                 }
4280         }
4281 }
4282
4283 #[test]
4284 fn test_claim_sizeable_push_msat() {
4285         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4286         let chanmon_cfgs = create_chanmon_cfgs(2);
4287         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4288         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4289         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4290
4291         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4292         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4293         check_closed_broadcast!(nodes[1], true);
4294         check_added_monitors!(nodes[1], 1);
4295         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4296         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4297         assert_eq!(node_txn.len(), 1);
4298         check_spends!(node_txn[0], chan.3);
4299         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
4300
4301         mine_transaction(&nodes[1], &node_txn[0]);
4302         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4303
4304         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4305         assert_eq!(spend_txn.len(), 1);
4306         assert_eq!(spend_txn[0].input.len(), 1);
4307         check_spends!(spend_txn[0], node_txn[0]);
4308         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4309 }
4310
4311 #[test]
4312 fn test_claim_on_remote_sizeable_push_msat() {
4313         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4314         // to_remote output is encumbered by a P2WPKH
4315         let chanmon_cfgs = create_chanmon_cfgs(2);
4316         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4317         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4318         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4319
4320         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4321         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4322         check_closed_broadcast!(nodes[0], true);
4323         check_added_monitors!(nodes[0], 1);
4324         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4325
4326         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4327         assert_eq!(node_txn.len(), 1);
4328         check_spends!(node_txn[0], chan.3);
4329         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
4330
4331         mine_transaction(&nodes[1], &node_txn[0]);
4332         check_closed_broadcast!(nodes[1], true);
4333         check_added_monitors!(nodes[1], 1);
4334         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4335         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4336
4337         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4338         assert_eq!(spend_txn.len(), 1);
4339         check_spends!(spend_txn[0], node_txn[0]);
4340 }
4341
4342 #[test]
4343 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4344         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4345         // to_remote output is encumbered by a P2WPKH
4346
4347         let chanmon_cfgs = create_chanmon_cfgs(2);
4348         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4349         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4350         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4351
4352         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4353         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4354         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4355         assert_eq!(revoked_local_txn[0].input.len(), 1);
4356         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4357
4358         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4359         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4360         check_closed_broadcast!(nodes[1], true);
4361         check_added_monitors!(nodes[1], 1);
4362         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4363
4364         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4365         mine_transaction(&nodes[1], &node_txn[0]);
4366         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4367
4368         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4369         assert_eq!(spend_txn.len(), 3);
4370         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4371         check_spends!(spend_txn[1], node_txn[0]);
4372         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4373 }
4374
4375 #[test]
4376 fn test_static_spendable_outputs_preimage_tx() {
4377         let chanmon_cfgs = create_chanmon_cfgs(2);
4378         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4379         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4380         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4381
4382         // Create some initial channels
4383         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4384
4385         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4386
4387         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4388         assert_eq!(commitment_tx[0].input.len(), 1);
4389         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4390
4391         // Settle A's commitment tx on B's chain
4392         nodes[1].node.claim_funds(payment_preimage);
4393         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4394         check_added_monitors!(nodes[1], 1);
4395         mine_transaction(&nodes[1], &commitment_tx[0]);
4396         check_added_monitors!(nodes[1], 1);
4397         let events = nodes[1].node.get_and_clear_pending_msg_events();
4398         match events[0] {
4399                 MessageSendEvent::UpdateHTLCs { .. } => {},
4400                 _ => panic!("Unexpected event"),
4401         }
4402         match events[1] {
4403                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4404                 _ => panic!("Unexepected event"),
4405         }
4406
4407         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4408         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4409         assert_eq!(node_txn.len(), 1);
4410         check_spends!(node_txn[0], commitment_tx[0]);
4411         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4412
4413         mine_transaction(&nodes[1], &node_txn[0]);
4414         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4415         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4416
4417         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4418         assert_eq!(spend_txn.len(), 1);
4419         check_spends!(spend_txn[0], node_txn[0]);
4420 }
4421
4422 #[test]
4423 fn test_static_spendable_outputs_timeout_tx() {
4424         let chanmon_cfgs = create_chanmon_cfgs(2);
4425         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4426         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4427         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4428
4429         // Create some initial channels
4430         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4431
4432         // Rebalance the network a bit by relaying one payment through all the channels ...
4433         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4434
4435         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4436
4437         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4438         assert_eq!(commitment_tx[0].input.len(), 1);
4439         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4440
4441         // Settle A's commitment tx on B' chain
4442         mine_transaction(&nodes[1], &commitment_tx[0]);
4443         check_added_monitors!(nodes[1], 1);
4444         let events = nodes[1].node.get_and_clear_pending_msg_events();
4445         match events[0] {
4446                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4447                 _ => panic!("Unexpected event"),
4448         }
4449         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4450
4451         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4452         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4453         assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4454         check_spends!(node_txn[0],  commitment_tx[0].clone());
4455         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4456
4457         mine_transaction(&nodes[1], &node_txn[0]);
4458         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4459         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4460         expect_payment_failed!(nodes[1], our_payment_hash, false);
4461
4462         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4463         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4464         check_spends!(spend_txn[0], commitment_tx[0]);
4465         check_spends!(spend_txn[1], node_txn[0]);
4466         check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4467 }
4468
4469 #[test]
4470 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4471         let chanmon_cfgs = create_chanmon_cfgs(2);
4472         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4473         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4474         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4475
4476         // Create some initial channels
4477         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4478
4479         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4480         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4481         assert_eq!(revoked_local_txn[0].input.len(), 1);
4482         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4483
4484         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4485
4486         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4487         check_closed_broadcast!(nodes[1], true);
4488         check_added_monitors!(nodes[1], 1);
4489         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4490
4491         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4492         assert_eq!(node_txn.len(), 1);
4493         assert_eq!(node_txn[0].input.len(), 2);
4494         check_spends!(node_txn[0], revoked_local_txn[0]);
4495
4496         mine_transaction(&nodes[1], &node_txn[0]);
4497         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4498
4499         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4500         assert_eq!(spend_txn.len(), 1);
4501         check_spends!(spend_txn[0], node_txn[0]);
4502 }
4503
4504 #[test]
4505 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4506         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4507         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4508         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4509         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4510         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4511
4512         // Create some initial channels
4513         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4514
4515         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4516         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4517         assert_eq!(revoked_local_txn[0].input.len(), 1);
4518         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4519
4520         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4521
4522         // A will generate HTLC-Timeout from revoked commitment tx
4523         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4524         check_closed_broadcast!(nodes[0], true);
4525         check_added_monitors!(nodes[0], 1);
4526         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4527         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4528
4529         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4530         assert_eq!(revoked_htlc_txn.len(), 1);
4531         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4532         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4533         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4534         assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4535
4536         // B will generate justice tx from A's revoked commitment/HTLC tx
4537         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4538         check_closed_broadcast!(nodes[1], true);
4539         check_added_monitors!(nodes[1], 1);
4540         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4541
4542         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4543         assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4544         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4545         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4546         // transactions next...
4547         assert_eq!(node_txn[0].input.len(), 3);
4548         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4549
4550         assert_eq!(node_txn[1].input.len(), 2);
4551         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4552         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4553                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4554         } else {
4555                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4556                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4557         }
4558
4559         mine_transaction(&nodes[1], &node_txn[1]);
4560         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4561
4562         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4563         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4564         assert_eq!(spend_txn.len(), 1);
4565         assert_eq!(spend_txn[0].input.len(), 1);
4566         check_spends!(spend_txn[0], node_txn[1]);
4567 }
4568
4569 #[test]
4570 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4571         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4572         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4573         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4574         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4575         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4576
4577         // Create some initial channels
4578         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4579
4580         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4581         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4582         assert_eq!(revoked_local_txn[0].input.len(), 1);
4583         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4584
4585         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4586         assert_eq!(revoked_local_txn[0].output.len(), 2);
4587
4588         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4589
4590         // B will generate HTLC-Success from revoked commitment tx
4591         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4592         check_closed_broadcast!(nodes[1], true);
4593         check_added_monitors!(nodes[1], 1);
4594         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4595         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4596
4597         assert_eq!(revoked_htlc_txn.len(), 1);
4598         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4599         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4600         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4601
4602         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4603         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4604         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4605
4606         // A will generate justice tx from B's revoked commitment/HTLC tx
4607         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4608         check_closed_broadcast!(nodes[0], true);
4609         check_added_monitors!(nodes[0], 1);
4610         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4611
4612         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4613         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4614
4615         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4616         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4617         // transactions next...
4618         assert_eq!(node_txn[0].input.len(), 2);
4619         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4620         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4621                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4622         } else {
4623                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4624                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4625         }
4626
4627         assert_eq!(node_txn[1].input.len(), 1);
4628         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4629
4630         mine_transaction(&nodes[0], &node_txn[1]);
4631         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4632
4633         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4634         // didn't try to generate any new transactions.
4635
4636         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4637         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4638         assert_eq!(spend_txn.len(), 3);
4639         assert_eq!(spend_txn[0].input.len(), 1);
4640         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4641         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4642         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4643         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4644 }
4645
4646 #[test]
4647 fn test_onchain_to_onchain_claim() {
4648         // Test that in case of channel closure, we detect the state of output and claim HTLC
4649         // on downstream peer's remote commitment tx.
4650         // First, have C claim an HTLC against its own latest commitment transaction.
4651         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4652         // channel.
4653         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4654         // gets broadcast.
4655
4656         let chanmon_cfgs = create_chanmon_cfgs(3);
4657         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4658         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4659         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4660
4661         // Create some initial channels
4662         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4663         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4664
4665         // Ensure all nodes are at the same height
4666         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4667         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4668         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4669         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4670
4671         // Rebalance the network a bit by relaying one payment through all the channels ...
4672         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4673         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4674
4675         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4676         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4677         check_spends!(commitment_tx[0], chan_2.3);
4678         nodes[2].node.claim_funds(payment_preimage);
4679         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4680         check_added_monitors!(nodes[2], 1);
4681         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4682         assert!(updates.update_add_htlcs.is_empty());
4683         assert!(updates.update_fail_htlcs.is_empty());
4684         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4685         assert!(updates.update_fail_malformed_htlcs.is_empty());
4686
4687         mine_transaction(&nodes[2], &commitment_tx[0]);
4688         check_closed_broadcast!(nodes[2], true);
4689         check_added_monitors!(nodes[2], 1);
4690         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4691
4692         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4693         assert_eq!(c_txn.len(), 1);
4694         check_spends!(c_txn[0], commitment_tx[0]);
4695         assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4696         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4697         assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4698
4699         // 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
4700         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), c_txn[0].clone()]));
4701         check_added_monitors!(nodes[1], 1);
4702         let events = nodes[1].node.get_and_clear_pending_events();
4703         assert_eq!(events.len(), 2);
4704         match events[0] {
4705                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4706                 _ => panic!("Unexpected event"),
4707         }
4708         match events[1] {
4709                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4710                         assert_eq!(fee_earned_msat, Some(1000));
4711                         assert_eq!(prev_channel_id, Some(chan_1.2));
4712                         assert_eq!(claim_from_onchain_tx, true);
4713                         assert_eq!(next_channel_id, Some(chan_2.2));
4714                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4715                 },
4716                 _ => panic!("Unexpected event"),
4717         }
4718         check_added_monitors!(nodes[1], 1);
4719         let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4720         assert_eq!(msg_events.len(), 3);
4721         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4722         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4723
4724         match nodes_2_event {
4725                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4726                 _ => panic!("Unexpected event"),
4727         }
4728
4729         match nodes_0_event {
4730                 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, .. } } => {
4731                         assert!(update_add_htlcs.is_empty());
4732                         assert!(update_fail_htlcs.is_empty());
4733                         assert_eq!(update_fulfill_htlcs.len(), 1);
4734                         assert!(update_fail_malformed_htlcs.is_empty());
4735                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4736                 },
4737                 _ => panic!("Unexpected event"),
4738         };
4739
4740         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4741         match msg_events[0] {
4742                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4743                 _ => panic!("Unexpected event"),
4744         }
4745
4746         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4747         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4748         mine_transaction(&nodes[1], &commitment_tx[0]);
4749         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4750         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4751         // ChannelMonitor: HTLC-Success tx
4752         assert_eq!(b_txn.len(), 1);
4753         check_spends!(b_txn[0], commitment_tx[0]);
4754         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4755         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4756         assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1); // Success tx
4757
4758         check_closed_broadcast!(nodes[1], true);
4759         check_added_monitors!(nodes[1], 1);
4760 }
4761
4762 #[test]
4763 fn test_duplicate_payment_hash_one_failure_one_success() {
4764         // Topology : A --> B --> C --> D
4765         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4766         // Note that because C will refuse to generate two payment secrets for the same payment hash,
4767         // we forward one of the payments onwards to D.
4768         let chanmon_cfgs = create_chanmon_cfgs(4);
4769         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4770         // When this test was written, the default base fee floated based on the HTLC count.
4771         // It is now fixed, so we simply set the fee to the expected value here.
4772         let mut config = test_default_channel_config();
4773         config.channel_config.forwarding_fee_base_msat = 196;
4774         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4775                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4776         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4777
4778         create_announced_chan_between_nodes(&nodes, 0, 1);
4779         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4780         create_announced_chan_between_nodes(&nodes, 2, 3);
4781
4782         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4783         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4784         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4785         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4786         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4787
4788         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4789
4790         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4791         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4792         // script push size limit so that the below script length checks match
4793         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4794         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4795                 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
4796         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000);
4797         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4798
4799         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4800         assert_eq!(commitment_txn[0].input.len(), 1);
4801         check_spends!(commitment_txn[0], chan_2.3);
4802
4803         mine_transaction(&nodes[1], &commitment_txn[0]);
4804         check_closed_broadcast!(nodes[1], true);
4805         check_added_monitors!(nodes[1], 1);
4806         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4807         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
4808
4809         let htlc_timeout_tx;
4810         { // Extract one of the two HTLC-Timeout transaction
4811                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4812                 // ChannelMonitor: timeout tx * 2-or-3
4813                 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4814
4815                 check_spends!(node_txn[0], commitment_txn[0]);
4816                 assert_eq!(node_txn[0].input.len(), 1);
4817                 assert_eq!(node_txn[0].output.len(), 1);
4818
4819                 if node_txn.len() > 2 {
4820                         check_spends!(node_txn[1], commitment_txn[0]);
4821                         assert_eq!(node_txn[1].input.len(), 1);
4822                         assert_eq!(node_txn[1].output.len(), 1);
4823                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4824
4825                         check_spends!(node_txn[2], commitment_txn[0]);
4826                         assert_eq!(node_txn[2].input.len(), 1);
4827                         assert_eq!(node_txn[2].output.len(), 1);
4828                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4829                 } else {
4830                         check_spends!(node_txn[1], commitment_txn[0]);
4831                         assert_eq!(node_txn[1].input.len(), 1);
4832                         assert_eq!(node_txn[1].output.len(), 1);
4833                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4834                 }
4835
4836                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4837                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4838                 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
4839                 // (with value 900 sats) will be claimed in the below `claim_funds` call.
4840                 if node_txn.len() > 2 {
4841                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4842                         htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
4843                 } else {
4844                         htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
4845                 }
4846         }
4847
4848         nodes[2].node.claim_funds(our_payment_preimage);
4849         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4850
4851         mine_transaction(&nodes[2], &commitment_txn[0]);
4852         check_added_monitors!(nodes[2], 2);
4853         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4854         let events = nodes[2].node.get_and_clear_pending_msg_events();
4855         match events[0] {
4856                 MessageSendEvent::UpdateHTLCs { .. } => {},
4857                 _ => panic!("Unexpected event"),
4858         }
4859         match events[1] {
4860                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4861                 _ => panic!("Unexepected event"),
4862         }
4863         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4864         assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4865         check_spends!(htlc_success_txn[0], commitment_txn[0]);
4866         check_spends!(htlc_success_txn[1], commitment_txn[0]);
4867         assert_eq!(htlc_success_txn[0].input.len(), 1);
4868         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4869         assert_eq!(htlc_success_txn[1].input.len(), 1);
4870         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4871         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4872         assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4873
4874         mine_transaction(&nodes[1], &htlc_timeout_tx);
4875         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4876         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 }]);
4877         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4878         assert!(htlc_updates.update_add_htlcs.is_empty());
4879         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4880         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4881         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4882         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4883         check_added_monitors!(nodes[1], 1);
4884
4885         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4886         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4887         {
4888                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4889         }
4890         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
4891
4892         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4893         mine_transaction(&nodes[1], &htlc_success_txn[1]);
4894         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
4895         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4896         assert!(updates.update_add_htlcs.is_empty());
4897         assert!(updates.update_fail_htlcs.is_empty());
4898         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4899         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
4900         assert!(updates.update_fail_malformed_htlcs.is_empty());
4901         check_added_monitors!(nodes[1], 1);
4902
4903         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4904         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4905         expect_payment_sent(&nodes[0], our_payment_preimage, None, true);
4906 }
4907
4908 #[test]
4909 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4910         let chanmon_cfgs = create_chanmon_cfgs(2);
4911         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4912         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4913         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4914
4915         // Create some initial channels
4916         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4917
4918         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
4919         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4920         assert_eq!(local_txn.len(), 1);
4921         assert_eq!(local_txn[0].input.len(), 1);
4922         check_spends!(local_txn[0], chan_1.3);
4923
4924         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4925         nodes[1].node.claim_funds(payment_preimage);
4926         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
4927         check_added_monitors!(nodes[1], 1);
4928
4929         mine_transaction(&nodes[1], &local_txn[0]);
4930         check_added_monitors!(nodes[1], 1);
4931         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4932         let events = nodes[1].node.get_and_clear_pending_msg_events();
4933         match events[0] {
4934                 MessageSendEvent::UpdateHTLCs { .. } => {},
4935                 _ => panic!("Unexpected event"),
4936         }
4937         match events[1] {
4938                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4939                 _ => panic!("Unexepected event"),
4940         }
4941         let node_tx = {
4942                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4943                 assert_eq!(node_txn.len(), 1);
4944                 assert_eq!(node_txn[0].input.len(), 1);
4945                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4946                 check_spends!(node_txn[0], local_txn[0]);
4947                 node_txn[0].clone()
4948         };
4949
4950         mine_transaction(&nodes[1], &node_tx);
4951         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4952
4953         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4954         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4955         assert_eq!(spend_txn.len(), 1);
4956         assert_eq!(spend_txn[0].input.len(), 1);
4957         check_spends!(spend_txn[0], node_tx);
4958         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4959 }
4960
4961 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4962         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4963         // unrevoked commitment transaction.
4964         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4965         // a remote RAA before they could be failed backwards (and combinations thereof).
4966         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4967         // use the same payment hashes.
4968         // Thus, we use a six-node network:
4969         //
4970         // A \         / E
4971         //    - C - D -
4972         // B /         \ F
4973         // And test where C fails back to A/B when D announces its latest commitment transaction
4974         let chanmon_cfgs = create_chanmon_cfgs(6);
4975         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4976         // When this test was written, the default base fee floated based on the HTLC count.
4977         // It is now fixed, so we simply set the fee to the expected value here.
4978         let mut config = test_default_channel_config();
4979         config.channel_config.forwarding_fee_base_msat = 196;
4980         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
4981                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4982         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4983
4984         let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
4985         let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4986         let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
4987         let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
4988         let chan_3_5  = create_announced_chan_between_nodes(&nodes, 3, 5);
4989
4990         // Rebalance and check output sanity...
4991         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
4992         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
4993         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
4994
4995         let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
4996                 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
4997         // 0th HTLC:
4998         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
4999         // 1st HTLC:
5000         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
5001         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5002         // 2nd HTLC:
5003         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
5004         // 3rd HTLC:
5005         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
5006         // 4th HTLC:
5007         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5008         // 5th HTLC:
5009         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5010         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5011         // 6th HTLC:
5012         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());
5013         // 7th HTLC:
5014         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());
5015
5016         // 8th HTLC:
5017         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5018         // 9th HTLC:
5019         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5020         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
5021
5022         // 10th HTLC:
5023         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
5024         // 11th HTLC:
5025         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5026         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());
5027
5028         // Double-check that six of the new HTLC were added
5029         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5030         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5031         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5032         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5033
5034         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5035         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5036         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5037         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5038         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5039         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5040         check_added_monitors!(nodes[4], 0);
5041
5042         let failed_destinations = vec![
5043                 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5044                 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5045                 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5046                 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5047         ];
5048         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5049         check_added_monitors!(nodes[4], 1);
5050
5051         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5052         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5053         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5054         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5055         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5056         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5057
5058         // Fail 3rd below-dust and 7th above-dust HTLCs
5059         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5060         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5061         check_added_monitors!(nodes[5], 0);
5062
5063         let failed_destinations_2 = vec![
5064                 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5065                 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5066         ];
5067         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5068         check_added_monitors!(nodes[5], 1);
5069
5070         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5071         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5072         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5073         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5074
5075         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5076
5077         // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5078         let failed_destinations_3 = vec![
5079                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5080                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5081                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5082                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5083                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5084                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5085         ];
5086         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5087         check_added_monitors!(nodes[3], 1);
5088         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5089         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5090         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5091         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5092         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5093         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5094         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5095         if deliver_last_raa {
5096                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5097         } else {
5098                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5099         }
5100
5101         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5102         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5103         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5104         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5105         //
5106         // We now broadcast the latest commitment transaction, which *should* result in failures for
5107         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5108         // the non-broadcast above-dust HTLCs.
5109         //
5110         // Alternatively, we may broadcast the previous commitment transaction, which should only
5111         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5112         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5113
5114         if announce_latest {
5115                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5116         } else {
5117                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5118         }
5119         let events = nodes[2].node.get_and_clear_pending_events();
5120         let close_event = if deliver_last_raa {
5121                 assert_eq!(events.len(), 2 + 6);
5122                 events.last().clone().unwrap()
5123         } else {
5124                 assert_eq!(events.len(), 1);
5125                 events.last().clone().unwrap()
5126         };
5127         match close_event {
5128                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5129                 _ => panic!("Unexpected event"),
5130         }
5131
5132         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5133         check_closed_broadcast!(nodes[2], true);
5134         if deliver_last_raa {
5135                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5136
5137                 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();
5138                 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5139         } else {
5140                 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5141                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5142                 } else {
5143                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5144                 };
5145
5146                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5147         }
5148         check_added_monitors!(nodes[2], 3);
5149
5150         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5151         assert_eq!(cs_msgs.len(), 2);
5152         let mut a_done = false;
5153         for msg in cs_msgs {
5154                 match msg {
5155                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5156                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5157                                 // should be failed-backwards here.
5158                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5159                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5160                                         for htlc in &updates.update_fail_htlcs {
5161                                                 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 });
5162                                         }
5163                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5164                                         assert!(!a_done);
5165                                         a_done = true;
5166                                         &nodes[0]
5167                                 } else {
5168                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5169                                         for htlc in &updates.update_fail_htlcs {
5170                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5171                                         }
5172                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5173                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5174                                         &nodes[1]
5175                                 };
5176                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5177                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5178                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5179                                 if announce_latest {
5180                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5181                                         if *node_id == nodes[0].node.get_our_node_id() {
5182                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5183                                         }
5184                                 }
5185                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5186                         },
5187                         _ => panic!("Unexpected event"),
5188                 }
5189         }
5190
5191         let as_events = nodes[0].node.get_and_clear_pending_events();
5192         assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5193         let mut as_failds = HashSet::new();
5194         let mut as_updates = 0;
5195         for event in as_events.iter() {
5196                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5197                         assert!(as_failds.insert(*payment_hash));
5198                         if *payment_hash != payment_hash_2 {
5199                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5200                         } else {
5201                                 assert!(!payment_failed_permanently);
5202                         }
5203                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5204                                 as_updates += 1;
5205                         }
5206                 } else if let &Event::PaymentFailed { .. } = event {
5207                 } else { panic!("Unexpected event"); }
5208         }
5209         assert!(as_failds.contains(&payment_hash_1));
5210         assert!(as_failds.contains(&payment_hash_2));
5211         if announce_latest {
5212                 assert!(as_failds.contains(&payment_hash_3));
5213                 assert!(as_failds.contains(&payment_hash_5));
5214         }
5215         assert!(as_failds.contains(&payment_hash_6));
5216
5217         let bs_events = nodes[1].node.get_and_clear_pending_events();
5218         assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5219         let mut bs_failds = HashSet::new();
5220         let mut bs_updates = 0;
5221         for event in bs_events.iter() {
5222                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5223                         assert!(bs_failds.insert(*payment_hash));
5224                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5225                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5226                         } else {
5227                                 assert!(!payment_failed_permanently);
5228                         }
5229                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5230                                 bs_updates += 1;
5231                         }
5232                 } else if let &Event::PaymentFailed { .. } = event {
5233                 } else { panic!("Unexpected event"); }
5234         }
5235         assert!(bs_failds.contains(&payment_hash_1));
5236         assert!(bs_failds.contains(&payment_hash_2));
5237         if announce_latest {
5238                 assert!(bs_failds.contains(&payment_hash_4));
5239         }
5240         assert!(bs_failds.contains(&payment_hash_5));
5241
5242         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5243         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5244         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5245         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5246         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5247         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5248 }
5249
5250 #[test]
5251 fn test_fail_backwards_latest_remote_announce_a() {
5252         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5253 }
5254
5255 #[test]
5256 fn test_fail_backwards_latest_remote_announce_b() {
5257         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5258 }
5259
5260 #[test]
5261 fn test_fail_backwards_previous_remote_announce() {
5262         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5263         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5264         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5265 }
5266
5267 #[test]
5268 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5269         let chanmon_cfgs = create_chanmon_cfgs(2);
5270         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5271         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5272         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5273
5274         // Create some initial channels
5275         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5276
5277         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5278         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5279         assert_eq!(local_txn[0].input.len(), 1);
5280         check_spends!(local_txn[0], chan_1.3);
5281
5282         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5283         mine_transaction(&nodes[0], &local_txn[0]);
5284         check_closed_broadcast!(nodes[0], true);
5285         check_added_monitors!(nodes[0], 1);
5286         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5287         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5288
5289         let htlc_timeout = {
5290                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5291                 assert_eq!(node_txn.len(), 1);
5292                 assert_eq!(node_txn[0].input.len(), 1);
5293                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5294                 check_spends!(node_txn[0], local_txn[0]);
5295                 node_txn[0].clone()
5296         };
5297
5298         mine_transaction(&nodes[0], &htlc_timeout);
5299         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5300         expect_payment_failed!(nodes[0], our_payment_hash, false);
5301
5302         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5303         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5304         assert_eq!(spend_txn.len(), 3);
5305         check_spends!(spend_txn[0], local_txn[0]);
5306         assert_eq!(spend_txn[1].input.len(), 1);
5307         check_spends!(spend_txn[1], htlc_timeout);
5308         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5309         assert_eq!(spend_txn[2].input.len(), 2);
5310         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5311         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5312                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5313 }
5314
5315 #[test]
5316 fn test_key_derivation_params() {
5317         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5318         // manager rotation to test that `channel_keys_id` returned in
5319         // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5320         // then derive a `delayed_payment_key`.
5321
5322         let chanmon_cfgs = create_chanmon_cfgs(3);
5323
5324         // We manually create the node configuration to backup the seed.
5325         let seed = [42; 32];
5326         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5327         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);
5328         let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5329         let scorer = Mutex::new(test_utils::TestScorer::new());
5330         let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5331         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)) };
5332         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5333         node_cfgs.remove(0);
5334         node_cfgs.insert(0, node);
5335
5336         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5337         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5338
5339         // Create some initial channels
5340         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5341         // for node 0
5342         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5343         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5344         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5345
5346         // Ensure all nodes are at the same height
5347         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5348         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5349         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5350         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5351
5352         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5353         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5354         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5355         assert_eq!(local_txn_1[0].input.len(), 1);
5356         check_spends!(local_txn_1[0], chan_1.3);
5357
5358         // We check funding pubkey are unique
5359         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]));
5360         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]));
5361         if from_0_funding_key_0 == from_1_funding_key_0
5362             || from_0_funding_key_0 == from_1_funding_key_1
5363             || from_0_funding_key_1 == from_1_funding_key_0
5364             || from_0_funding_key_1 == from_1_funding_key_1 {
5365                 panic!("Funding pubkeys aren't unique");
5366         }
5367
5368         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5369         mine_transaction(&nodes[0], &local_txn_1[0]);
5370         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5371         check_closed_broadcast!(nodes[0], true);
5372         check_added_monitors!(nodes[0], 1);
5373         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5374
5375         let htlc_timeout = {
5376                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5377                 assert_eq!(node_txn.len(), 1);
5378                 assert_eq!(node_txn[0].input.len(), 1);
5379                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5380                 check_spends!(node_txn[0], local_txn_1[0]);
5381                 node_txn[0].clone()
5382         };
5383
5384         mine_transaction(&nodes[0], &htlc_timeout);
5385         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5386         expect_payment_failed!(nodes[0], our_payment_hash, false);
5387
5388         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5389         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5390         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5391         assert_eq!(spend_txn.len(), 3);
5392         check_spends!(spend_txn[0], local_txn_1[0]);
5393         assert_eq!(spend_txn[1].input.len(), 1);
5394         check_spends!(spend_txn[1], htlc_timeout);
5395         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5396         assert_eq!(spend_txn[2].input.len(), 2);
5397         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5398         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5399                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5400 }
5401
5402 #[test]
5403 fn test_static_output_closing_tx() {
5404         let chanmon_cfgs = create_chanmon_cfgs(2);
5405         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5406         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5407         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5408
5409         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5410
5411         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5412         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5413
5414         mine_transaction(&nodes[0], &closing_tx);
5415         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5416         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5417
5418         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5419         assert_eq!(spend_txn.len(), 1);
5420         check_spends!(spend_txn[0], closing_tx);
5421
5422         mine_transaction(&nodes[1], &closing_tx);
5423         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5424         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5425
5426         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5427         assert_eq!(spend_txn.len(), 1);
5428         check_spends!(spend_txn[0], closing_tx);
5429 }
5430
5431 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5432         let chanmon_cfgs = create_chanmon_cfgs(2);
5433         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5434         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5435         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5436         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5437
5438         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5439
5440         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5441         // present in B's local commitment transaction, but none of A's commitment transactions.
5442         nodes[1].node.claim_funds(payment_preimage);
5443         check_added_monitors!(nodes[1], 1);
5444         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5445
5446         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5447         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5448         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5449
5450         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5451         check_added_monitors!(nodes[0], 1);
5452         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5453         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5454         check_added_monitors!(nodes[1], 1);
5455
5456         let starting_block = nodes[1].best_block_info();
5457         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5458         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5459                 connect_block(&nodes[1], &block);
5460                 block.header.prev_blockhash = block.block_hash();
5461         }
5462         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5463         check_closed_broadcast!(nodes[1], true);
5464         check_added_monitors!(nodes[1], 1);
5465         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5466 }
5467
5468 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5469         let chanmon_cfgs = create_chanmon_cfgs(2);
5470         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5471         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5472         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5473         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5474
5475         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5476         nodes[0].node.send_payment_with_route(&route, payment_hash,
5477                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5478         check_added_monitors!(nodes[0], 1);
5479
5480         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5481
5482         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5483         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5484         // to "time out" the HTLC.
5485
5486         let starting_block = nodes[1].best_block_info();
5487         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5488
5489         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5490                 connect_block(&nodes[0], &block);
5491                 block.header.prev_blockhash = block.block_hash();
5492         }
5493         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5494         check_closed_broadcast!(nodes[0], true);
5495         check_added_monitors!(nodes[0], 1);
5496         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5497 }
5498
5499 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5500         let chanmon_cfgs = create_chanmon_cfgs(3);
5501         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5502         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5503         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5504         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5505
5506         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5507         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5508         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5509         // actually revoked.
5510         let htlc_value = if use_dust { 50000 } else { 3000000 };
5511         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5512         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5513         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5514         check_added_monitors!(nodes[1], 1);
5515
5516         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5517         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5518         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5519         check_added_monitors!(nodes[0], 1);
5520         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5521         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5522         check_added_monitors!(nodes[1], 1);
5523         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5524         check_added_monitors!(nodes[1], 1);
5525         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5526
5527         if check_revoke_no_close {
5528                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5529                 check_added_monitors!(nodes[0], 1);
5530         }
5531
5532         let starting_block = nodes[1].best_block_info();
5533         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5534         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5535                 connect_block(&nodes[0], &block);
5536                 block.header.prev_blockhash = block.block_hash();
5537         }
5538         if !check_revoke_no_close {
5539                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5540                 check_closed_broadcast!(nodes[0], true);
5541                 check_added_monitors!(nodes[0], 1);
5542                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5543         } else {
5544                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5545         }
5546 }
5547
5548 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5549 // There are only a few cases to test here:
5550 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5551 //    broadcastable commitment transactions result in channel closure,
5552 //  * its included in an unrevoked-but-previous remote commitment transaction,
5553 //  * its included in the latest remote or local commitment transactions.
5554 // We test each of the three possible commitment transactions individually and use both dust and
5555 // non-dust HTLCs.
5556 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5557 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5558 // tested for at least one of the cases in other tests.
5559 #[test]
5560 fn htlc_claim_single_commitment_only_a() {
5561         do_htlc_claim_local_commitment_only(true);
5562         do_htlc_claim_local_commitment_only(false);
5563
5564         do_htlc_claim_current_remote_commitment_only(true);
5565         do_htlc_claim_current_remote_commitment_only(false);
5566 }
5567
5568 #[test]
5569 fn htlc_claim_single_commitment_only_b() {
5570         do_htlc_claim_previous_remote_commitment_only(true, false);
5571         do_htlc_claim_previous_remote_commitment_only(false, false);
5572         do_htlc_claim_previous_remote_commitment_only(true, true);
5573         do_htlc_claim_previous_remote_commitment_only(false, true);
5574 }
5575
5576 #[test]
5577 #[should_panic]
5578 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5579         let chanmon_cfgs = create_chanmon_cfgs(2);
5580         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5581         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5582         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5583         // Force duplicate randomness for every get-random call
5584         for node in nodes.iter() {
5585                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5586         }
5587
5588         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5589         let channel_value_satoshis=10000;
5590         let push_msat=10001;
5591         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5592         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5593         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5594         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5595
5596         // Create a second channel with the same random values. This used to panic due to a colliding
5597         // channel_id, but now panics due to a colliding outbound SCID alias.
5598         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5599 }
5600
5601 #[test]
5602 fn bolt2_open_channel_sending_node_checks_part2() {
5603         let chanmon_cfgs = create_chanmon_cfgs(2);
5604         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5605         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5606         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5607
5608         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5609         let channel_value_satoshis=2^24;
5610         let push_msat=10001;
5611         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5612
5613         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5614         let channel_value_satoshis=10000;
5615         // Test when push_msat is equal to 1000 * funding_satoshis.
5616         let push_msat=1000*channel_value_satoshis+1;
5617         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5618
5619         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5620         let channel_value_satoshis=10000;
5621         let push_msat=10001;
5622         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
5623         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5624         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5625
5626         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5627         // 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
5628         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5629
5630         // 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.
5631         assert!(BREAKDOWN_TIMEOUT>0);
5632         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5633
5634         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5635         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5636         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5637
5638         // 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.
5639         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5640         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5641         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5642         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5643         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5644 }
5645
5646 #[test]
5647 fn bolt2_open_channel_sane_dust_limit() {
5648         let chanmon_cfgs = create_chanmon_cfgs(2);
5649         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5650         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5651         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5652
5653         let channel_value_satoshis=1000000;
5654         let push_msat=10001;
5655         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5656         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5657         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5658         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5659
5660         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5661         let events = nodes[1].node.get_and_clear_pending_msg_events();
5662         let err_msg = match events[0] {
5663                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5664                         msg.clone()
5665                 },
5666                 _ => panic!("Unexpected event"),
5667         };
5668         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5669 }
5670
5671 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5672 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5673 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5674 // is no longer affordable once it's freed.
5675 #[test]
5676 fn test_fail_holding_cell_htlc_upon_free() {
5677         let chanmon_cfgs = create_chanmon_cfgs(2);
5678         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5679         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5680         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5681         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5682
5683         // First nodes[0] generates an update_fee, setting the channel's
5684         // pending_update_fee.
5685         {
5686                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5687                 *feerate_lock += 20;
5688         }
5689         nodes[0].node.timer_tick_occurred();
5690         check_added_monitors!(nodes[0], 1);
5691
5692         let events = nodes[0].node.get_and_clear_pending_msg_events();
5693         assert_eq!(events.len(), 1);
5694         let (update_msg, commitment_signed) = match events[0] {
5695                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5696                         (update_fee.as_ref(), commitment_signed)
5697                 },
5698                 _ => panic!("Unexpected event"),
5699         };
5700
5701         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5702
5703         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5704         let channel_reserve = chan_stat.channel_reserve_msat;
5705         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5706         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5707
5708         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5709         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5710         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5711
5712         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5713         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5714                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5715         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5716         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5717
5718         // Flush the pending fee update.
5719         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5720         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5721         check_added_monitors!(nodes[1], 1);
5722         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5723         check_added_monitors!(nodes[0], 1);
5724
5725         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5726         // HTLC, but now that the fee has been raised the payment will now fail, causing
5727         // us to surface its failure to the user.
5728         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5729         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5730         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);
5731         let failure_log = format!("Failed to send HTLC with payment_hash {} due to Cannot send value that would put our balance under counterparty-announced channel reserve value ({}) in channel {}",
5732                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5733         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5734
5735         // Check that the payment failed to be sent out.
5736         let events = nodes[0].node.get_and_clear_pending_events();
5737         assert_eq!(events.len(), 2);
5738         match &events[0] {
5739                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5740                         assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5741                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5742                         assert_eq!(*payment_failed_permanently, false);
5743                         assert_eq!(*short_channel_id, Some(route.paths[0].hops[0].short_channel_id));
5744                 },
5745                 _ => panic!("Unexpected event"),
5746         }
5747         match &events[1] {
5748                 &Event::PaymentFailed { ref payment_hash, .. } => {
5749                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5750                 },
5751                 _ => panic!("Unexpected event"),
5752         }
5753 }
5754
5755 // Test that if multiple HTLCs are released from the holding cell and one is
5756 // valid but the other is no longer valid upon release, the valid HTLC can be
5757 // successfully completed while the other one fails as expected.
5758 #[test]
5759 fn test_free_and_fail_holding_cell_htlcs() {
5760         let chanmon_cfgs = create_chanmon_cfgs(2);
5761         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5762         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5763         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5764         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5765
5766         // First nodes[0] generates an update_fee, setting the channel's
5767         // pending_update_fee.
5768         {
5769                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5770                 *feerate_lock += 200;
5771         }
5772         nodes[0].node.timer_tick_occurred();
5773         check_added_monitors!(nodes[0], 1);
5774
5775         let events = nodes[0].node.get_and_clear_pending_msg_events();
5776         assert_eq!(events.len(), 1);
5777         let (update_msg, commitment_signed) = match events[0] {
5778                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5779                         (update_fee.as_ref(), commitment_signed)
5780                 },
5781                 _ => panic!("Unexpected event"),
5782         };
5783
5784         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5785
5786         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5787         let channel_reserve = chan_stat.channel_reserve_msat;
5788         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5789         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5790
5791         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5792         let amt_1 = 20000;
5793         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
5794         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5795         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5796
5797         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5798         nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
5799                 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5800         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5801         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5802         let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5803         nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
5804                 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
5805         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5806         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5807
5808         // Flush the pending fee update.
5809         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5810         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5811         check_added_monitors!(nodes[1], 1);
5812         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5813         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5814         check_added_monitors!(nodes[0], 2);
5815
5816         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5817         // but now that the fee has been raised the second payment will now fail, causing us
5818         // to surface its failure to the user. The first payment should succeed.
5819         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5820         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5821         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Freeing holding cell with 2 HTLC updates in channel {}", hex::encode(chan.2)), 1);
5822         let failure_log = format!("Failed to send HTLC with payment_hash {} due to Cannot send value that would put our balance under counterparty-announced channel reserve value ({}) in channel {}",
5823                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5824         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5825
5826         // Check that the second payment failed to be sent out.
5827         let events = nodes[0].node.get_and_clear_pending_events();
5828         assert_eq!(events.len(), 2);
5829         match &events[0] {
5830                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5831                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5832                         assert_eq!(payment_hash_2.clone(), *payment_hash);
5833                         assert_eq!(*payment_failed_permanently, false);
5834                         assert_eq!(*short_channel_id, Some(route_2.paths[0].hops[0].short_channel_id));
5835                 },
5836                 _ => panic!("Unexpected event"),
5837         }
5838         match &events[1] {
5839                 &Event::PaymentFailed { ref payment_hash, .. } => {
5840                         assert_eq!(payment_hash_2.clone(), *payment_hash);
5841                 },
5842                 _ => panic!("Unexpected event"),
5843         }
5844
5845         // Complete the first payment and the RAA from the fee update.
5846         let (payment_event, send_raa_event) = {
5847                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5848                 assert_eq!(msgs.len(), 2);
5849                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5850         };
5851         let raa = match send_raa_event {
5852                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5853                 _ => panic!("Unexpected event"),
5854         };
5855         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5856         check_added_monitors!(nodes[1], 1);
5857         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5858         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5859         let events = nodes[1].node.get_and_clear_pending_events();
5860         assert_eq!(events.len(), 1);
5861         match events[0] {
5862                 Event::PendingHTLCsForwardable { .. } => {},
5863                 _ => panic!("Unexpected event"),
5864         }
5865         nodes[1].node.process_pending_htlc_forwards();
5866         let events = nodes[1].node.get_and_clear_pending_events();
5867         assert_eq!(events.len(), 1);
5868         match events[0] {
5869                 Event::PaymentClaimable { .. } => {},
5870                 _ => panic!("Unexpected event"),
5871         }
5872         nodes[1].node.claim_funds(payment_preimage_1);
5873         check_added_monitors!(nodes[1], 1);
5874         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5875
5876         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5877         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5878         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5879         expect_payment_sent!(nodes[0], payment_preimage_1);
5880 }
5881
5882 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
5883 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
5884 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
5885 // once it's freed.
5886 #[test]
5887 fn test_fail_holding_cell_htlc_upon_free_multihop() {
5888         let chanmon_cfgs = create_chanmon_cfgs(3);
5889         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5890         // Avoid having to include routing fees in calculations
5891         let mut config = test_default_channel_config();
5892         config.channel_config.forwarding_fee_base_msat = 0;
5893         config.channel_config.forwarding_fee_proportional_millionths = 0;
5894         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5895         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5896         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5897         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
5898
5899         // First nodes[1] generates an update_fee, setting the channel's
5900         // pending_update_fee.
5901         {
5902                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
5903                 *feerate_lock += 20;
5904         }
5905         nodes[1].node.timer_tick_occurred();
5906         check_added_monitors!(nodes[1], 1);
5907
5908         let events = nodes[1].node.get_and_clear_pending_msg_events();
5909         assert_eq!(events.len(), 1);
5910         let (update_msg, commitment_signed) = match events[0] {
5911                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5912                         (update_fee.as_ref(), commitment_signed)
5913                 },
5914                 _ => panic!("Unexpected event"),
5915         };
5916
5917         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
5918
5919         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
5920         let channel_reserve = chan_stat.channel_reserve_msat;
5921         let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
5922         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_0_1.2);
5923
5924         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5925         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5926         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
5927         let payment_event = {
5928                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5929                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5930                 check_added_monitors!(nodes[0], 1);
5931
5932                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5933                 assert_eq!(events.len(), 1);
5934
5935                 SendEvent::from_event(events.remove(0))
5936         };
5937         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5938         check_added_monitors!(nodes[1], 0);
5939         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5940         expect_pending_htlcs_forwardable!(nodes[1]);
5941
5942         chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
5943         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5944
5945         // Flush the pending fee update.
5946         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
5947         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5948         check_added_monitors!(nodes[2], 1);
5949         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
5950         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
5951         check_added_monitors!(nodes[1], 2);
5952
5953         // A final RAA message is generated to finalize the fee update.
5954         let events = nodes[1].node.get_and_clear_pending_msg_events();
5955         assert_eq!(events.len(), 1);
5956
5957         let raa_msg = match &events[0] {
5958                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
5959                         msg.clone()
5960                 },
5961                 _ => panic!("Unexpected event"),
5962         };
5963
5964         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
5965         check_added_monitors!(nodes[2], 1);
5966         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
5967
5968         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
5969         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
5970         assert_eq!(process_htlc_forwards_event.len(), 2);
5971         match &process_htlc_forwards_event[0] {
5972                 &Event::PendingHTLCsForwardable { .. } => {},
5973                 _ => panic!("Unexpected event"),
5974         }
5975
5976         // In response, we call ChannelManager's process_pending_htlc_forwards
5977         nodes[1].node.process_pending_htlc_forwards();
5978         check_added_monitors!(nodes[1], 1);
5979
5980         // This causes the HTLC to be failed backwards.
5981         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
5982         assert_eq!(fail_event.len(), 1);
5983         let (fail_msg, commitment_signed) = match &fail_event[0] {
5984                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
5985                         assert_eq!(updates.update_add_htlcs.len(), 0);
5986                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
5987                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
5988                         assert_eq!(updates.update_fail_htlcs.len(), 1);
5989                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
5990                 },
5991                 _ => panic!("Unexpected event"),
5992         };
5993
5994         // Pass the failure messages back to nodes[0].
5995         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5996         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5997
5998         // Complete the HTLC failure+removal process.
5999         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6000         check_added_monitors!(nodes[0], 1);
6001         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6002         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6003         check_added_monitors!(nodes[1], 2);
6004         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6005         assert_eq!(final_raa_event.len(), 1);
6006         let raa = match &final_raa_event[0] {
6007                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6008                 _ => panic!("Unexpected event"),
6009         };
6010         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6011         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6012         check_added_monitors!(nodes[0], 1);
6013 }
6014
6015 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6016 // 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.
6017 //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.
6018
6019 #[test]
6020 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6021         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6022         let chanmon_cfgs = create_chanmon_cfgs(2);
6023         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6024         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6025         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6026         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6027
6028         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6029         route.paths[0].hops[0].fee_msat = 100;
6030
6031         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6032                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6033                 ), true, APIError::ChannelUnavailable { ref err },
6034                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6035         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6036         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send less than their minimum HTLC value", 1);
6037 }
6038
6039 #[test]
6040 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6041         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6042         let chanmon_cfgs = create_chanmon_cfgs(2);
6043         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6044         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6045         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6046         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6047
6048         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6049         route.paths[0].hops[0].fee_msat = 0;
6050         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6051                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6052                 true, APIError::ChannelUnavailable { ref err },
6053                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6054
6055         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6056         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6057 }
6058
6059 #[test]
6060 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6061         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6062         let chanmon_cfgs = create_chanmon_cfgs(2);
6063         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6064         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6065         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6066         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6067
6068         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6069         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6070                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6071         check_added_monitors!(nodes[0], 1);
6072         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6073         updates.update_add_htlcs[0].amount_msat = 0;
6074
6075         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6076         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6077         check_closed_broadcast!(nodes[1], true).unwrap();
6078         check_added_monitors!(nodes[1], 1);
6079         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6080 }
6081
6082 #[test]
6083 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6084         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6085         //It is enforced when constructing a route.
6086         let chanmon_cfgs = create_chanmon_cfgs(2);
6087         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6088         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6089         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6090         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6091
6092         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6093                 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
6094         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6095         route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;
6096         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6097                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6098                 ), true, APIError::InvalidRoute { ref err },
6099                 assert_eq!(err, &"Channel CLTV overflowed?"));
6100 }
6101
6102 #[test]
6103 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6104         //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.
6105         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6106         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6107         let chanmon_cfgs = create_chanmon_cfgs(2);
6108         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6109         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6110         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6111         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6112         let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6113                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6114
6115         for i in 0..max_accepted_htlcs {
6116                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6117                 let payment_event = {
6118                         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6119                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6120                         check_added_monitors!(nodes[0], 1);
6121
6122                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6123                         assert_eq!(events.len(), 1);
6124                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6125                                 assert_eq!(htlcs[0].htlc_id, i);
6126                         } else {
6127                                 assert!(false);
6128                         }
6129                         SendEvent::from_event(events.remove(0))
6130                 };
6131                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6132                 check_added_monitors!(nodes[1], 0);
6133                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6134
6135                 expect_pending_htlcs_forwardable!(nodes[1]);
6136                 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6137         }
6138         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
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 { ref err },
6142                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6143
6144         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6145         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
6146 }
6147
6148 #[test]
6149 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6150         //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.
6151         let chanmon_cfgs = create_chanmon_cfgs(2);
6152         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6153         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6154         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6155         let channel_value = 100000;
6156         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6157         let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6158
6159         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6160
6161         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6162         // Manually create a route over our max in flight (which our router normally automatically
6163         // limits us to.
6164         route.paths[0].hops[0].fee_msat =  max_in_flight + 1;
6165         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6166                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6167                 ), true, APIError::ChannelUnavailable { ref err },
6168                 assert!(regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap().is_match(err)));
6169
6170         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6171         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put us over the max HTLC value in flight our peer will accept", 1);
6172
6173         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6174 }
6175
6176 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6177 #[test]
6178 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6179         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6180         let chanmon_cfgs = create_chanmon_cfgs(2);
6181         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6182         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6183         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6184         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6185         let htlc_minimum_msat: u64;
6186         {
6187                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6188                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6189                 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6190                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6191         }
6192
6193         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6194         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6195                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6196         check_added_monitors!(nodes[0], 1);
6197         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6198         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6199         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6200         assert!(nodes[1].node.list_channels().is_empty());
6201         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6202         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()));
6203         check_added_monitors!(nodes[1], 1);
6204         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6205 }
6206
6207 #[test]
6208 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6209         //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
6210         let chanmon_cfgs = create_chanmon_cfgs(2);
6211         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6212         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6213         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6214         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6215
6216         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6217         let channel_reserve = chan_stat.channel_reserve_msat;
6218         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6219         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
6220         // The 2* and +1 are for the fee spike reserve.
6221         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6222
6223         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6224         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6225         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6226                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6227         check_added_monitors!(nodes[0], 1);
6228         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6229
6230         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6231         // at this time channel-initiatee receivers are not required to enforce that senders
6232         // respect the fee_spike_reserve.
6233         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6234         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6235
6236         assert!(nodes[1].node.list_channels().is_empty());
6237         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6238         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6239         check_added_monitors!(nodes[1], 1);
6240         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6241 }
6242
6243 #[test]
6244 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6245         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6246         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6247         let chanmon_cfgs = create_chanmon_cfgs(2);
6248         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6249         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6250         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6251         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6252
6253         let send_amt = 3999999;
6254         let (mut route, our_payment_hash, _, our_payment_secret) =
6255                 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
6256         route.paths[0].hops[0].fee_msat = send_amt;
6257         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6258         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6259         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6260         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6261                 &route.paths[0], send_amt, RecipientOnionFields::secret_only(our_payment_secret), cur_height, &None).unwrap();
6262         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
6263
6264         let mut msg = msgs::UpdateAddHTLC {
6265                 channel_id: chan.2,
6266                 htlc_id: 0,
6267                 amount_msat: 1000,
6268                 payment_hash: our_payment_hash,
6269                 cltv_expiry: htlc_cltv,
6270                 onion_routing_packet: onion_packet.clone(),
6271         };
6272
6273         for i in 0..50 {
6274                 msg.htlc_id = i as u64;
6275                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6276         }
6277         msg.htlc_id = (50) as u64;
6278         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6279
6280         assert!(nodes[1].node.list_channels().is_empty());
6281         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6282         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6283         check_added_monitors!(nodes[1], 1);
6284         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6285 }
6286
6287 #[test]
6288 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6289         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6290         let chanmon_cfgs = create_chanmon_cfgs(2);
6291         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6292         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6293         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6294         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6295
6296         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6297         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6298                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6299         check_added_monitors!(nodes[0], 1);
6300         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6301         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;
6302         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6303
6304         assert!(nodes[1].node.list_channels().is_empty());
6305         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6306         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6307         check_added_monitors!(nodes[1], 1);
6308         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6309 }
6310
6311 #[test]
6312 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6313         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6314         let chanmon_cfgs = create_chanmon_cfgs(2);
6315         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6316         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6317         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6318
6319         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6320         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6321         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6322                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6323         check_added_monitors!(nodes[0], 1);
6324         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6325         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6326         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6327
6328         assert!(nodes[1].node.list_channels().is_empty());
6329         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6330         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6331         check_added_monitors!(nodes[1], 1);
6332         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6333 }
6334
6335 #[test]
6336 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6337         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6338         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6339         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6340         let chanmon_cfgs = create_chanmon_cfgs(2);
6341         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6342         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6343         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6344
6345         create_announced_chan_between_nodes(&nodes, 0, 1);
6346         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6347         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6348                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6349         check_added_monitors!(nodes[0], 1);
6350         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6351         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6352
6353         //Disconnect and Reconnect
6354         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6355         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6356         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }, true).unwrap();
6357         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6358         assert_eq!(reestablish_1.len(), 1);
6359         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }, false).unwrap();
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().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().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 Channel::new_outbound()
6965         if let Err(error) = Channel::new_outbound(&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 Channel::new_from_req()
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) = Channel::new_from_req(&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 Channel::new_from_req()
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) = Channel::new_from_req(&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 { features: nodes[1].node.init_features(), remote_network_address: None }, true).unwrap();
7123         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7124         assert_eq!(reestablish_1.len(), 3);
7125         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }, false).unwrap();
7126         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7127         assert_eq!(reestablish_2.len(), 3);
7128
7129         // Reestablish chan_1
7130         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7131         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7132         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7133         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7134         // Reestablish chan_2
7135         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7136         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7137         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7138         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7139         // Reestablish chan_3
7140         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7141         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7142         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7143         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7144
7145         for _ in 0..ENABLE_GOSSIP_TICKS {
7146                 nodes[0].node.timer_tick_occurred();
7147         }
7148         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7149         nodes[0].node.timer_tick_occurred();
7150         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7151         assert_eq!(msg_events.len(), 3);
7152         for e in msg_events {
7153                 match e {
7154                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7155                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7156                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7157                                         // Each update should have a higher timestamp than the previous one, replacing
7158                                         // the old one.
7159                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7160                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7161                                 }
7162                         },
7163                         _ => panic!("Unexpected event"),
7164                 }
7165         }
7166         // Check that each channel gets updated exactly once
7167         assert!(chans_disabled.is_empty());
7168 }
7169
7170 #[test]
7171 fn test_bump_penalty_txn_on_revoked_commitment() {
7172         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7173         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7174
7175         let chanmon_cfgs = create_chanmon_cfgs(2);
7176         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7177         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7178         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7179
7180         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7181
7182         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7183         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7184                 .with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7185         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000);
7186         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7187
7188         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7189         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7190         assert_eq!(revoked_txn[0].output.len(), 4);
7191         assert_eq!(revoked_txn[0].input.len(), 1);
7192         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7193         let revoked_txid = revoked_txn[0].txid();
7194
7195         let mut penalty_sum = 0;
7196         for outp in revoked_txn[0].output.iter() {
7197                 if outp.script_pubkey.is_v0_p2wsh() {
7198                         penalty_sum += outp.value;
7199                 }
7200         }
7201
7202         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7203         let header_114 = connect_blocks(&nodes[1], 14);
7204
7205         // Actually revoke tx by claiming a HTLC
7206         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7207         connect_block(&nodes[1], &create_dummy_block(header_114, 42, vec![revoked_txn[0].clone()]));
7208         check_added_monitors!(nodes[1], 1);
7209
7210         // One or more justice tx should have been broadcast, check it
7211         let penalty_1;
7212         let feerate_1;
7213         {
7214                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7215                 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7216                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7217                 assert_eq!(node_txn[0].output.len(), 1);
7218                 check_spends!(node_txn[0], revoked_txn[0]);
7219                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7220                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7221                 penalty_1 = node_txn[0].txid();
7222                 node_txn.clear();
7223         };
7224
7225         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7226         connect_blocks(&nodes[1], 15);
7227         let mut penalty_2 = penalty_1;
7228         let mut feerate_2 = 0;
7229         {
7230                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7231                 assert_eq!(node_txn.len(), 1);
7232                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7233                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7234                         assert_eq!(node_txn[0].output.len(), 1);
7235                         check_spends!(node_txn[0], revoked_txn[0]);
7236                         penalty_2 = node_txn[0].txid();
7237                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7238                         assert_ne!(penalty_2, penalty_1);
7239                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7240                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7241                         // Verify 25% bump heuristic
7242                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7243                         node_txn.clear();
7244                 }
7245         }
7246         assert_ne!(feerate_2, 0);
7247
7248         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7249         connect_blocks(&nodes[1], 1);
7250         let penalty_3;
7251         let mut feerate_3 = 0;
7252         {
7253                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7254                 assert_eq!(node_txn.len(), 1);
7255                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7256                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7257                         assert_eq!(node_txn[0].output.len(), 1);
7258                         check_spends!(node_txn[0], revoked_txn[0]);
7259                         penalty_3 = node_txn[0].txid();
7260                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7261                         assert_ne!(penalty_3, penalty_2);
7262                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7263                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7264                         // Verify 25% bump heuristic
7265                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7266                         node_txn.clear();
7267                 }
7268         }
7269         assert_ne!(feerate_3, 0);
7270
7271         nodes[1].node.get_and_clear_pending_events();
7272         nodes[1].node.get_and_clear_pending_msg_events();
7273 }
7274
7275 #[test]
7276 fn test_bump_penalty_txn_on_revoked_htlcs() {
7277         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7278         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7279
7280         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7281         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7282         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7283         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7284         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7285
7286         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7287         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7288         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7289         let scorer = test_utils::TestScorer::new();
7290         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7291         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7292                 3_000_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7293         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7294         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7295         let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7296                 3_000_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7297         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7298
7299         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7300         assert_eq!(revoked_local_txn[0].input.len(), 1);
7301         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7302
7303         // Revoke local commitment tx
7304         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7305
7306         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7307         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone()]));
7308         check_closed_broadcast!(nodes[1], true);
7309         check_added_monitors!(nodes[1], 1);
7310         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7311         connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7312
7313         let revoked_htlc_txn = {
7314                 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7315                 assert_eq!(txn.len(), 2);
7316
7317                 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7318                 assert_eq!(txn[0].input.len(), 1);
7319                 check_spends!(txn[0], revoked_local_txn[0]);
7320
7321                 assert_eq!(txn[1].input.len(), 1);
7322                 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7323                 assert_eq!(txn[1].output.len(), 1);
7324                 check_spends!(txn[1], revoked_local_txn[0]);
7325
7326                 txn
7327         };
7328
7329         // Broadcast set of revoked txn on A
7330         let hash_128 = connect_blocks(&nodes[0], 40);
7331         let block_11 = create_dummy_block(hash_128, 42, vec![revoked_local_txn[0].clone()]);
7332         connect_block(&nodes[0], &block_11);
7333         let block_129 = create_dummy_block(block_11.block_hash(), 42, vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()]);
7334         connect_block(&nodes[0], &block_129);
7335         let events = nodes[0].node.get_and_clear_pending_events();
7336         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7337         match events.last().unwrap() {
7338                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7339                 _ => panic!("Unexpected event"),
7340         }
7341         let first;
7342         let feerate_1;
7343         let penalty_txn;
7344         {
7345                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7346                 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7347                 // Verify claim tx are spending revoked HTLC txn
7348
7349                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7350                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7351                 // which are included in the same block (they are broadcasted because we scan the
7352                 // transactions linearly and generate claims as we go, they likely should be removed in the
7353                 // future).
7354                 assert_eq!(node_txn[0].input.len(), 1);
7355                 check_spends!(node_txn[0], revoked_local_txn[0]);
7356                 assert_eq!(node_txn[1].input.len(), 1);
7357                 check_spends!(node_txn[1], revoked_local_txn[0]);
7358                 assert_eq!(node_txn[2].input.len(), 1);
7359                 check_spends!(node_txn[2], revoked_local_txn[0]);
7360
7361                 // Each of the three justice transactions claim a separate (single) output of the three
7362                 // available, which we check here:
7363                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7364                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7365                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7366
7367                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7368                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7369
7370                 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7371                 // output, checked above).
7372                 assert_eq!(node_txn[3].input.len(), 2);
7373                 assert_eq!(node_txn[3].output.len(), 1);
7374                 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7375
7376                 first = node_txn[3].txid();
7377                 // Store both feerates for later comparison
7378                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7379                 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7380                 penalty_txn = vec![node_txn[2].clone()];
7381                 node_txn.clear();
7382         }
7383
7384         // Connect one more block to see if bumped penalty are issued for HTLC txn
7385         let block_130 = create_dummy_block(block_129.block_hash(), 42, penalty_txn);
7386         connect_block(&nodes[0], &block_130);
7387         let block_131 = create_dummy_block(block_130.block_hash(), 42, Vec::new());
7388         connect_block(&nodes[0], &block_131);
7389
7390         // Few more blocks to confirm penalty txn
7391         connect_blocks(&nodes[0], 4);
7392         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7393         let header_144 = connect_blocks(&nodes[0], 9);
7394         let node_txn = {
7395                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7396                 assert_eq!(node_txn.len(), 1);
7397
7398                 assert_eq!(node_txn[0].input.len(), 2);
7399                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7400                 // Verify bumped tx is different and 25% bump heuristic
7401                 assert_ne!(first, node_txn[0].txid());
7402                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7403                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7404                 assert!(feerate_2 * 100 > feerate_1 * 125);
7405                 let txn = vec![node_txn[0].clone()];
7406                 node_txn.clear();
7407                 txn
7408         };
7409         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7410         connect_block(&nodes[0], &create_dummy_block(header_144, 42, node_txn));
7411         connect_blocks(&nodes[0], 20);
7412         {
7413                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7414                 // We verify than no new transaction has been broadcast because previously
7415                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7416                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7417                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7418                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7419                 // up bumped justice generation.
7420                 assert_eq!(node_txn.len(), 0);
7421                 node_txn.clear();
7422         }
7423         check_closed_broadcast!(nodes[0], true);
7424         check_added_monitors!(nodes[0], 1);
7425 }
7426
7427 #[test]
7428 fn test_bump_penalty_txn_on_remote_commitment() {
7429         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7430         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7431
7432         // Create 2 HTLCs
7433         // Provide preimage for one
7434         // Check aggregation
7435
7436         let chanmon_cfgs = create_chanmon_cfgs(2);
7437         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7438         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7439         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7440
7441         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7442         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7443         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7444
7445         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7446         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7447         assert_eq!(remote_txn[0].output.len(), 4);
7448         assert_eq!(remote_txn[0].input.len(), 1);
7449         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7450
7451         // Claim a HTLC without revocation (provide B monitor with preimage)
7452         nodes[1].node.claim_funds(payment_preimage);
7453         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7454         mine_transaction(&nodes[1], &remote_txn[0]);
7455         check_added_monitors!(nodes[1], 2);
7456         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7457
7458         // One or more claim tx should have been broadcast, check it
7459         let timeout;
7460         let preimage;
7461         let preimage_bump;
7462         let feerate_timeout;
7463         let feerate_preimage;
7464         {
7465                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7466                 // 3 transactions including:
7467                 //   preimage and timeout sweeps from remote commitment + preimage sweep bump
7468                 assert_eq!(node_txn.len(), 3);
7469                 assert_eq!(node_txn[0].input.len(), 1);
7470                 assert_eq!(node_txn[1].input.len(), 1);
7471                 assert_eq!(node_txn[2].input.len(), 1);
7472                 check_spends!(node_txn[0], remote_txn[0]);
7473                 check_spends!(node_txn[1], remote_txn[0]);
7474                 check_spends!(node_txn[2], remote_txn[0]);
7475
7476                 preimage = node_txn[0].txid();
7477                 let index = node_txn[0].input[0].previous_output.vout;
7478                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7479                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7480
7481                 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7482                         (node_txn[2].clone(), node_txn[1].clone())
7483                 } else {
7484                         (node_txn[1].clone(), node_txn[2].clone())
7485                 };
7486
7487                 preimage_bump = preimage_bump_tx;
7488                 check_spends!(preimage_bump, remote_txn[0]);
7489                 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7490
7491                 timeout = timeout_tx.txid();
7492                 let index = timeout_tx.input[0].previous_output.vout;
7493                 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7494                 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7495
7496                 node_txn.clear();
7497         };
7498         assert_ne!(feerate_timeout, 0);
7499         assert_ne!(feerate_preimage, 0);
7500
7501         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7502         connect_blocks(&nodes[1], 1);
7503         {
7504                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7505                 assert_eq!(node_txn.len(), 1);
7506                 assert_eq!(node_txn[0].input.len(), 1);
7507                 assert_eq!(preimage_bump.input.len(), 1);
7508                 check_spends!(node_txn[0], remote_txn[0]);
7509                 check_spends!(preimage_bump, remote_txn[0]);
7510
7511                 let index = preimage_bump.input[0].previous_output.vout;
7512                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7513                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7514                 assert!(new_feerate * 100 > feerate_timeout * 125);
7515                 assert_ne!(timeout, preimage_bump.txid());
7516
7517                 let index = node_txn[0].input[0].previous_output.vout;
7518                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7519                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7520                 assert!(new_feerate * 100 > feerate_preimage * 125);
7521                 assert_ne!(preimage, node_txn[0].txid());
7522
7523                 node_txn.clear();
7524         }
7525
7526         nodes[1].node.get_and_clear_pending_events();
7527         nodes[1].node.get_and_clear_pending_msg_events();
7528 }
7529
7530 #[test]
7531 fn test_counterparty_raa_skip_no_crash() {
7532         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7533         // commitment transaction, we would have happily carried on and provided them the next
7534         // commitment transaction based on one RAA forward. This would probably eventually have led to
7535         // channel closure, but it would not have resulted in funds loss. Still, our
7536         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7537         // check simply that the channel is closed in response to such an RAA, but don't check whether
7538         // we decide to punish our counterparty for revoking their funds (as we don't currently
7539         // implement that).
7540         let chanmon_cfgs = create_chanmon_cfgs(2);
7541         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7542         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7543         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7544         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7545
7546         let per_commitment_secret;
7547         let next_per_commitment_point;
7548         {
7549                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7550                 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7551                 let keys = guard.channel_by_id.get_mut(&channel_id).unwrap().get_signer();
7552
7553                 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7554
7555                 // Make signer believe we got a counterparty signature, so that it allows the revocation
7556                 keys.get_enforcement_state().last_holder_commitment -= 1;
7557                 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7558
7559                 // Must revoke without gaps
7560                 keys.get_enforcement_state().last_holder_commitment -= 1;
7561                 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7562
7563                 keys.get_enforcement_state().last_holder_commitment -= 1;
7564                 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7565                         &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7566         }
7567
7568         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7569                 &msgs::RevokeAndACK {
7570                         channel_id,
7571                         per_commitment_secret,
7572                         next_per_commitment_point,
7573                         #[cfg(taproot)]
7574                         next_local_nonce: None,
7575                 });
7576         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7577         check_added_monitors!(nodes[1], 1);
7578         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7579 }
7580
7581 #[test]
7582 fn test_bump_txn_sanitize_tracking_maps() {
7583         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7584         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7585
7586         let chanmon_cfgs = create_chanmon_cfgs(2);
7587         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7588         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7589         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7590
7591         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7592         // Lock HTLC in both directions
7593         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7594         let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7595
7596         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7597         assert_eq!(revoked_local_txn[0].input.len(), 1);
7598         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7599
7600         // Revoke local commitment tx
7601         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7602
7603         // Broadcast set of revoked txn on A
7604         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7605         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7606         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7607
7608         mine_transaction(&nodes[0], &revoked_local_txn[0]);
7609         check_closed_broadcast!(nodes[0], true);
7610         check_added_monitors!(nodes[0], 1);
7611         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7612         let penalty_txn = {
7613                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7614                 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7615                 check_spends!(node_txn[0], revoked_local_txn[0]);
7616                 check_spends!(node_txn[1], revoked_local_txn[0]);
7617                 check_spends!(node_txn[2], revoked_local_txn[0]);
7618                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7619                 node_txn.clear();
7620                 penalty_txn
7621         };
7622         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, penalty_txn));
7623         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7624         {
7625                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7626                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7627                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7628         }
7629 }
7630
7631 #[test]
7632 fn test_channel_conf_timeout() {
7633         // Tests that, for inbound channels, we give up on them if the funding transaction does not
7634         // confirm within 2016 blocks, as recommended by BOLT 2.
7635         let chanmon_cfgs = create_chanmon_cfgs(2);
7636         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7637         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7638         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7639
7640         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7641
7642         // The outbound node should wait forever for confirmation:
7643         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7644         // copied here instead of directly referencing the constant.
7645         connect_blocks(&nodes[0], 2016);
7646         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7647
7648         // The inbound node should fail the channel after exactly 2016 blocks
7649         connect_blocks(&nodes[1], 2015);
7650         check_added_monitors!(nodes[1], 0);
7651         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7652
7653         connect_blocks(&nodes[1], 1);
7654         check_added_monitors!(nodes[1], 1);
7655         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
7656         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7657         assert_eq!(close_ev.len(), 1);
7658         match close_ev[0] {
7659                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7660                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7661                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7662                 },
7663                 _ => panic!("Unexpected event"),
7664         }
7665 }
7666
7667 #[test]
7668 fn test_override_channel_config() {
7669         let chanmon_cfgs = create_chanmon_cfgs(2);
7670         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7671         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7672         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7673
7674         // Node0 initiates a channel to node1 using the override config.
7675         let mut override_config = UserConfig::default();
7676         override_config.channel_handshake_config.our_to_self_delay = 200;
7677
7678         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7679
7680         // Assert the channel created by node0 is using the override config.
7681         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7682         assert_eq!(res.channel_flags, 0);
7683         assert_eq!(res.to_self_delay, 200);
7684 }
7685
7686 #[test]
7687 fn test_override_0msat_htlc_minimum() {
7688         let mut zero_config = UserConfig::default();
7689         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7690         let chanmon_cfgs = create_chanmon_cfgs(2);
7691         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7692         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7693         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7694
7695         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7696         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7697         assert_eq!(res.htlc_minimum_msat, 1);
7698
7699         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7700         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7701         assert_eq!(res.htlc_minimum_msat, 1);
7702 }
7703
7704 #[test]
7705 fn test_channel_update_has_correct_htlc_maximum_msat() {
7706         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7707         // Bolt 7 specifies that if present `htlc_maximum_msat`:
7708         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7709         // 90% of the `channel_value`.
7710         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7711
7712         let mut config_30_percent = UserConfig::default();
7713         config_30_percent.channel_handshake_config.announced_channel = true;
7714         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7715         let mut config_50_percent = UserConfig::default();
7716         config_50_percent.channel_handshake_config.announced_channel = true;
7717         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7718         let mut config_95_percent = UserConfig::default();
7719         config_95_percent.channel_handshake_config.announced_channel = true;
7720         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7721         let mut config_100_percent = UserConfig::default();
7722         config_100_percent.channel_handshake_config.announced_channel = true;
7723         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7724
7725         let chanmon_cfgs = create_chanmon_cfgs(4);
7726         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7727         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)]);
7728         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7729
7730         let channel_value_satoshis = 100000;
7731         let channel_value_msat = channel_value_satoshis * 1000;
7732         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7733         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7734         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7735
7736         let (node_0_chan_update, node_1_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7737         let (node_2_chan_update, node_3_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7738
7739         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7740         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7741         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7742         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7743         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7744         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7745
7746         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7747         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7748         // `channel_value`.
7749         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7750         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7751         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7752         // `channel_value`.
7753         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7754 }
7755
7756 #[test]
7757 fn test_manually_accept_inbound_channel_request() {
7758         let mut manually_accept_conf = UserConfig::default();
7759         manually_accept_conf.manually_accept_inbound_channels = true;
7760         let chanmon_cfgs = create_chanmon_cfgs(2);
7761         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7762         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7763         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7764
7765         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7766         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7767
7768         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7769
7770         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7771         // accepting the inbound channel request.
7772         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7773
7774         let events = nodes[1].node.get_and_clear_pending_events();
7775         match events[0] {
7776                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7777                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7778                 }
7779                 _ => panic!("Unexpected event"),
7780         }
7781
7782         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7783         assert_eq!(accept_msg_ev.len(), 1);
7784
7785         match accept_msg_ev[0] {
7786                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7787                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7788                 }
7789                 _ => panic!("Unexpected event"),
7790         }
7791
7792         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7793
7794         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7795         assert_eq!(close_msg_ev.len(), 1);
7796
7797         let events = nodes[1].node.get_and_clear_pending_events();
7798         match events[0] {
7799                 Event::ChannelClosed { user_channel_id, .. } => {
7800                         assert_eq!(user_channel_id, 23);
7801                 }
7802                 _ => panic!("Unexpected event"),
7803         }
7804 }
7805
7806 #[test]
7807 fn test_manually_reject_inbound_channel_request() {
7808         let mut manually_accept_conf = UserConfig::default();
7809         manually_accept_conf.manually_accept_inbound_channels = true;
7810         let chanmon_cfgs = create_chanmon_cfgs(2);
7811         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7812         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7813         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7814
7815         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7816         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7817
7818         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7819
7820         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7821         // rejecting the inbound channel request.
7822         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7823
7824         let events = nodes[1].node.get_and_clear_pending_events();
7825         match events[0] {
7826                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7827                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7828                 }
7829                 _ => panic!("Unexpected event"),
7830         }
7831
7832         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7833         assert_eq!(close_msg_ev.len(), 1);
7834
7835         match close_msg_ev[0] {
7836                 MessageSendEvent::HandleError { ref node_id, .. } => {
7837                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7838                 }
7839                 _ => panic!("Unexpected event"),
7840         }
7841         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
7842 }
7843
7844 #[test]
7845 fn test_reject_funding_before_inbound_channel_accepted() {
7846         // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
7847         // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
7848         // the node operator before the counterparty sends a `FundingCreated` message. If a
7849         // `FundingCreated` message is received before the channel is accepted, it should be rejected
7850         // and the channel should be closed.
7851         let mut manually_accept_conf = UserConfig::default();
7852         manually_accept_conf.manually_accept_inbound_channels = true;
7853         let chanmon_cfgs = create_chanmon_cfgs(2);
7854         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7855         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7856         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7857
7858         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7859         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7860         let temp_channel_id = res.temporary_channel_id;
7861
7862         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7863
7864         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
7865         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7866
7867         // Clear the `Event::OpenChannelRequest` event without responding to the request.
7868         nodes[1].node.get_and_clear_pending_events();
7869
7870         // Get the `AcceptChannel` message of `nodes[1]` without calling
7871         // `ChannelManager::accept_inbound_channel`, which generates a
7872         // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
7873         // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
7874         // succeed when `nodes[0]` is passed to it.
7875         let accept_chan_msg = {
7876                 let mut node_1_per_peer_lock;
7877                 let mut node_1_peer_state_lock;
7878                 let channel =  get_channel_ref!(&nodes[1], nodes[0], node_1_per_peer_lock, node_1_peer_state_lock, temp_channel_id);
7879                 channel.get_accept_channel_message()
7880         };
7881         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
7882
7883         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
7884
7885         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
7886         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
7887
7888         // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
7889         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
7890
7891         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7892         assert_eq!(close_msg_ev.len(), 1);
7893
7894         let expected_err = "FundingCreated message received before the channel was accepted";
7895         match close_msg_ev[0] {
7896                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
7897                         assert_eq!(msg.channel_id, temp_channel_id);
7898                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7899                         assert_eq!(msg.data, expected_err);
7900                 }
7901                 _ => panic!("Unexpected event"),
7902         }
7903
7904         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
7905 }
7906
7907 #[test]
7908 fn test_can_not_accept_inbound_channel_twice() {
7909         let mut manually_accept_conf = UserConfig::default();
7910         manually_accept_conf.manually_accept_inbound_channels = true;
7911         let chanmon_cfgs = create_chanmon_cfgs(2);
7912         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7913         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7914         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7915
7916         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7917         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7918
7919         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7920
7921         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7922         // accepting the inbound channel request.
7923         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7924
7925         let events = nodes[1].node.get_and_clear_pending_events();
7926         match events[0] {
7927                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7928                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7929                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7930                         match api_res {
7931                                 Err(APIError::APIMisuseError { err }) => {
7932                                         assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
7933                                 },
7934                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7935                                 Err(_) => panic!("Unexpected Error"),
7936                         }
7937                 }
7938                 _ => panic!("Unexpected event"),
7939         }
7940
7941         // Ensure that the channel wasn't closed after attempting to accept it twice.
7942         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7943         assert_eq!(accept_msg_ev.len(), 1);
7944
7945         match accept_msg_ev[0] {
7946                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7947                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7948                 }
7949                 _ => panic!("Unexpected event"),
7950         }
7951 }
7952
7953 #[test]
7954 fn test_can_not_accept_unknown_inbound_channel() {
7955         let chanmon_cfg = create_chanmon_cfgs(2);
7956         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
7957         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
7958         let nodes = create_network(2, &node_cfg, &node_chanmgr);
7959
7960         let unknown_channel_id = [0; 32];
7961         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
7962         match api_res {
7963                 Err(APIError::ChannelUnavailable { err }) => {
7964                         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()));
7965                 },
7966                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
7967                 Err(_) => panic!("Unexpected Error"),
7968         }
7969 }
7970
7971 #[test]
7972 fn test_onion_value_mpp_set_calculation() {
7973         // Test that we use the onion value `amt_to_forward` when
7974         // calculating whether we've reached the `total_msat` of an MPP
7975         // by having a routing node forward more than `amt_to_forward`
7976         // and checking that the receiving node doesn't generate
7977         // a PaymentClaimable event too early
7978         let node_count = 4;
7979         let chanmon_cfgs = create_chanmon_cfgs(node_count);
7980         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
7981         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
7982         let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
7983
7984         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
7985         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
7986         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
7987         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
7988
7989         let total_msat = 100_000;
7990         let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
7991         let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
7992         let sample_path = route.paths.pop().unwrap();
7993
7994         let mut path_1 = sample_path.clone();
7995         path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
7996         path_1.hops[0].short_channel_id = chan_1_id;
7997         path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
7998         path_1.hops[1].short_channel_id = chan_3_id;
7999         path_1.hops[1].fee_msat = 100_000;
8000         route.paths.push(path_1);
8001
8002         let mut path_2 = sample_path.clone();
8003         path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
8004         path_2.hops[0].short_channel_id = chan_2_id;
8005         path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
8006         path_2.hops[1].short_channel_id = chan_4_id;
8007         path_2.hops[1].fee_msat = 1_000;
8008         route.paths.push(path_2);
8009
8010         // Send payment
8011         let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
8012         let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
8013                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8014         nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
8015                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8016         check_added_monitors!(nodes[0], expected_paths.len());
8017
8018         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8019         assert_eq!(events.len(), expected_paths.len());
8020
8021         // First path
8022         let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8023         let mut payment_event = SendEvent::from_event(ev);
8024         let mut prev_node = &nodes[0];
8025
8026         for (idx, &node) in expected_paths[0].iter().enumerate() {
8027                 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8028
8029                 if idx == 0 { // routing node
8030                         let session_priv = [3; 32];
8031                         let height = nodes[0].best_block_info().1;
8032                         let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8033                         let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8034                         let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8035                                 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8036                         // Edit amt_to_forward to simulate the sender having set
8037                         // the final amount and the routing node taking less fee
8038                         onion_payloads[1].amt_to_forward = 99_000;
8039                         let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
8040                         payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8041                 }
8042
8043                 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8044                 check_added_monitors!(node, 0);
8045                 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8046                 expect_pending_htlcs_forwardable!(node);
8047
8048                 if idx == 0 {
8049                         let mut events_2 = node.node.get_and_clear_pending_msg_events();
8050                         assert_eq!(events_2.len(), 1);
8051                         check_added_monitors!(node, 1);
8052                         payment_event = SendEvent::from_event(events_2.remove(0));
8053                         assert_eq!(payment_event.msgs.len(), 1);
8054                 } else {
8055                         let events_2 = node.node.get_and_clear_pending_events();
8056                         assert!(events_2.is_empty());
8057                 }
8058
8059                 prev_node = node;
8060         }
8061
8062         // Second path
8063         let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8064         pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8065
8066         claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8067 }
8068
8069 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8070
8071         let routing_node_count = msat_amounts.len();
8072         let node_count = routing_node_count + 2;
8073
8074         let chanmon_cfgs = create_chanmon_cfgs(node_count);
8075         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8076         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8077         let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8078
8079         let src_idx = 0;
8080         let dst_idx = 1;
8081
8082         // Create channels for each amount
8083         let mut expected_paths = Vec::with_capacity(routing_node_count);
8084         let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8085         let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8086         for i in 0..routing_node_count {
8087                 let routing_node = 2 + i;
8088                 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8089                 src_chan_ids.push(src_chan_id);
8090                 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8091                 dst_chan_ids.push(dst_chan_id);
8092                 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8093                 expected_paths.push(path);
8094         }
8095         let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8096
8097         // Create a route for each amount
8098         let example_amount = 100000;
8099         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);
8100         let sample_path = route.paths.pop().unwrap();
8101         for i in 0..routing_node_count {
8102                 let routing_node = 2 + i;
8103                 let mut path = sample_path.clone();
8104                 path.hops[0].pubkey = nodes[routing_node].node.get_our_node_id();
8105                 path.hops[0].short_channel_id = src_chan_ids[i];
8106                 path.hops[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8107                 path.hops[1].short_channel_id = dst_chan_ids[i];
8108                 path.hops[1].fee_msat = msat_amounts[i];
8109                 route.paths.push(path);
8110         }
8111
8112         // Send payment with manually set total_msat
8113         let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8114         let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8115                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8116         nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8117                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8118         check_added_monitors!(nodes[src_idx], expected_paths.len());
8119
8120         let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8121         assert_eq!(events.len(), expected_paths.len());
8122         let mut amount_received = 0;
8123         for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8124                 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8125
8126                 let current_path_amount = msat_amounts[path_idx];
8127                 amount_received += current_path_amount;
8128                 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8129                 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8130         }
8131
8132         claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8133 }
8134
8135 #[test]
8136 fn test_overshoot_mpp() {
8137         do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8138         do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8139 }
8140
8141 #[test]
8142 fn test_simple_mpp() {
8143         // Simple test of sending a multi-path payment.
8144         let chanmon_cfgs = create_chanmon_cfgs(4);
8145         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8146         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8147         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8148
8149         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8150         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8151         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8152         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8153
8154         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8155         let path = route.paths[0].clone();
8156         route.paths.push(path);
8157         route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
8158         route.paths[0].hops[0].short_channel_id = chan_1_id;
8159         route.paths[0].hops[1].short_channel_id = chan_3_id;
8160         route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
8161         route.paths[1].hops[0].short_channel_id = chan_2_id;
8162         route.paths[1].hops[1].short_channel_id = chan_4_id;
8163         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8164         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8165 }
8166
8167 #[test]
8168 fn test_preimage_storage() {
8169         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8170         let chanmon_cfgs = create_chanmon_cfgs(2);
8171         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8172         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8173         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8174
8175         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8176
8177         {
8178                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8179                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8180                 nodes[0].node.send_payment_with_route(&route, payment_hash,
8181                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8182                 check_added_monitors!(nodes[0], 1);
8183                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8184                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8185                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8186                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8187         }
8188         // Note that after leaving the above scope we have no knowledge of any arguments or return
8189         // values from previous calls.
8190         expect_pending_htlcs_forwardable!(nodes[1]);
8191         let events = nodes[1].node.get_and_clear_pending_events();
8192         assert_eq!(events.len(), 1);
8193         match events[0] {
8194                 Event::PaymentClaimable { ref purpose, .. } => {
8195                         match &purpose {
8196                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8197                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8198                                 },
8199                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8200                         }
8201                 },
8202                 _ => panic!("Unexpected event"),
8203         }
8204 }
8205
8206 #[test]
8207 #[allow(deprecated)]
8208 fn test_secret_timeout() {
8209         // Simple test of payment secret storage time outs. After
8210         // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8211         let chanmon_cfgs = create_chanmon_cfgs(2);
8212         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8213         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8214         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8215
8216         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8217
8218         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8219
8220         // We should fail to register the same payment hash twice, at least until we've connected a
8221         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8222         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8223                 assert_eq!(err, "Duplicate payment hash");
8224         } else { panic!(); }
8225         let mut block = {
8226                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8227                 create_dummy_block(node_1_blocks.last().unwrap().0.block_hash(), node_1_blocks.len() as u32 + 7200, Vec::new())
8228         };
8229         connect_block(&nodes[1], &block);
8230         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8231                 assert_eq!(err, "Duplicate payment hash");
8232         } else { panic!(); }
8233
8234         // If we then connect the second block, we should be able to register the same payment hash
8235         // again (this time getting a new payment secret).
8236         block.header.prev_blockhash = block.header.block_hash();
8237         block.header.time += 1;
8238         connect_block(&nodes[1], &block);
8239         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8240         assert_ne!(payment_secret_1, our_payment_secret);
8241
8242         {
8243                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8244                 nodes[0].node.send_payment_with_route(&route, payment_hash,
8245                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(payment_hash.0)).unwrap();
8246                 check_added_monitors!(nodes[0], 1);
8247                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8248                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8249                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8250                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8251         }
8252         // Note that after leaving the above scope we have no knowledge of any arguments or return
8253         // values from previous calls.
8254         expect_pending_htlcs_forwardable!(nodes[1]);
8255         let events = nodes[1].node.get_and_clear_pending_events();
8256         assert_eq!(events.len(), 1);
8257         match events[0] {
8258                 Event::PaymentClaimable { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8259                         assert!(payment_preimage.is_none());
8260                         assert_eq!(payment_secret, our_payment_secret);
8261                         // We don't actually have the payment preimage with which to claim this payment!
8262                 },
8263                 _ => panic!("Unexpected event"),
8264         }
8265 }
8266
8267 #[test]
8268 fn test_bad_secret_hash() {
8269         // Simple test of unregistered payment hash/invalid payment secret handling
8270         let chanmon_cfgs = create_chanmon_cfgs(2);
8271         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8272         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8273         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8274
8275         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8276
8277         let random_payment_hash = PaymentHash([42; 32]);
8278         let random_payment_secret = PaymentSecret([43; 32]);
8279         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8280         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8281
8282         // All the below cases should end up being handled exactly identically, so we macro the
8283         // resulting events.
8284         macro_rules! handle_unknown_invalid_payment_data {
8285                 ($payment_hash: expr) => {
8286                         check_added_monitors!(nodes[0], 1);
8287                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8288                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8289                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8290                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8291
8292                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8293                         // again to process the pending backwards-failure of the HTLC
8294                         expect_pending_htlcs_forwardable!(nodes[1]);
8295                         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8296                         check_added_monitors!(nodes[1], 1);
8297
8298                         // We should fail the payment back
8299                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8300                         match events.pop().unwrap() {
8301                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8302                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8303                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8304                                 },
8305                                 _ => panic!("Unexpected event"),
8306                         }
8307                 }
8308         }
8309
8310         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8311         // Error data is the HTLC value (100,000) and current block height
8312         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8313
8314         // Send a payment with the right payment hash but the wrong payment secret
8315         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8316                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8317         handle_unknown_invalid_payment_data!(our_payment_hash);
8318         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8319
8320         // Send a payment with a random payment hash, but the right payment secret
8321         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8322                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8323         handle_unknown_invalid_payment_data!(random_payment_hash);
8324         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8325
8326         // Send a payment with a random payment hash and random payment secret
8327         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8328                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8329         handle_unknown_invalid_payment_data!(random_payment_hash);
8330         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8331 }
8332
8333 #[test]
8334 fn test_update_err_monitor_lockdown() {
8335         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8336         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8337         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8338         // error.
8339         //
8340         // This scenario may happen in a watchtower setup, where watchtower process a block height
8341         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8342         // commitment at same time.
8343
8344         let chanmon_cfgs = create_chanmon_cfgs(2);
8345         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8346         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8347         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8348
8349         // Create some initial channel
8350         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8351         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8352
8353         // Rebalance the network to generate htlc in the two directions
8354         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8355
8356         // Route a HTLC from node 0 to node 1 (but don't settle)
8357         let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8358
8359         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8360         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8361         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8362         let persister = test_utils::TestPersister::new();
8363         let watchtower = {
8364                 let new_monitor = {
8365                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8366                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8367                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8368                         assert!(new_monitor == *monitor);
8369                         new_monitor
8370                 };
8371                 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);
8372                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8373                 watchtower
8374         };
8375         let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8376         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8377         // transaction lock time requirements here.
8378         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8379         watchtower.chain_monitor.block_connected(&block, 200);
8380
8381         // Try to update ChannelMonitor
8382         nodes[1].node.claim_funds(preimage);
8383         check_added_monitors!(nodes[1], 1);
8384         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8385
8386         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8387         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8388         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8389         {
8390                 let mut node_0_per_peer_lock;
8391                 let mut node_0_peer_state_lock;
8392                 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8393                 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8394                         assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8395                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8396                 } else { assert!(false); }
8397         }
8398         // Our local monitor is in-sync and hasn't processed yet timeout
8399         check_added_monitors!(nodes[0], 1);
8400         let events = nodes[0].node.get_and_clear_pending_events();
8401         assert_eq!(events.len(), 1);
8402 }
8403
8404 #[test]
8405 fn test_concurrent_monitor_claim() {
8406         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8407         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8408         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8409         // state N+1 confirms. Alice claims output from state N+1.
8410
8411         let chanmon_cfgs = create_chanmon_cfgs(2);
8412         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8413         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8414         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8415
8416         // Create some initial channel
8417         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8418         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8419
8420         // Rebalance the network to generate htlc in the two directions
8421         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8422
8423         // Route a HTLC from node 0 to node 1 (but don't settle)
8424         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8425
8426         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8427         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8428         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8429         let persister = test_utils::TestPersister::new();
8430         let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8431                 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8432         );
8433         let watchtower_alice = {
8434                 let new_monitor = {
8435                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8436                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8437                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8438                         assert!(new_monitor == *monitor);
8439                         new_monitor
8440                 };
8441                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &alice_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8442                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8443                 watchtower
8444         };
8445         let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8446         // Make Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8447         // requirements here.
8448         const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8449         alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8450         watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8451
8452         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8453         let alice_state = {
8454                 let mut txn = alice_broadcaster.txn_broadcast();
8455                 assert_eq!(txn.len(), 2);
8456                 txn.remove(0)
8457         };
8458
8459         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8460         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8461         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8462         let persister = test_utils::TestPersister::new();
8463         let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8464         let watchtower_bob = {
8465                 let new_monitor = {
8466                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8467                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8468                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8469                         assert!(new_monitor == *monitor);
8470                         new_monitor
8471                 };
8472                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8473                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8474                 watchtower
8475         };
8476         watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST - 1);
8477
8478         // Route another payment to generate another update with still previous HTLC pending
8479         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8480         nodes[1].node.send_payment_with_route(&route, payment_hash,
8481                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8482         check_added_monitors!(nodes[1], 1);
8483
8484         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8485         assert_eq!(updates.update_add_htlcs.len(), 1);
8486         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8487         {
8488                 let mut node_0_per_peer_lock;
8489                 let mut node_0_peer_state_lock;
8490                 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8491                 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8492                         // Watchtower Alice should already have seen the block and reject the update
8493                         assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8494                         assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8495                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8496                 } else { assert!(false); }
8497         }
8498         // Our local monitor is in-sync and hasn't processed yet timeout
8499         check_added_monitors!(nodes[0], 1);
8500
8501         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8502         watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST);
8503
8504         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8505         let bob_state_y;
8506         {
8507                 let mut txn = bob_broadcaster.txn_broadcast();
8508                 assert_eq!(txn.len(), 2);
8509                 bob_state_y = txn.remove(0);
8510         };
8511
8512         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8513         let height = HTLC_TIMEOUT_BROADCAST + 1;
8514         connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
8515         check_closed_broadcast(&nodes[0], 1, true);
8516         check_closed_event(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false);
8517         watchtower_alice.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, vec![bob_state_y.clone()]), height);
8518         check_added_monitors(&nodes[0], 1);
8519         {
8520                 let htlc_txn = alice_broadcaster.txn_broadcast();
8521                 assert_eq!(htlc_txn.len(), 2);
8522                 check_spends!(htlc_txn[0], bob_state_y);
8523                 // Alice doesn't clean up the old HTLC claim since it hasn't seen a conflicting spend for
8524                 // it. However, she should, because it now has an invalid parent.
8525                 check_spends!(htlc_txn[1], alice_state);
8526         }
8527 }
8528
8529 #[test]
8530 fn test_pre_lockin_no_chan_closed_update() {
8531         // Test that if a peer closes a channel in response to a funding_created message we don't
8532         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8533         // message).
8534         //
8535         // Doing so would imply a channel monitor update before the initial channel monitor
8536         // registration, violating our API guarantees.
8537         //
8538         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8539         // then opening a second channel with the same funding output as the first (which is not
8540         // rejected because the first channel does not exist in the ChannelManager) and closing it
8541         // before receiving funding_signed.
8542         let chanmon_cfgs = create_chanmon_cfgs(2);
8543         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8544         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8545         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8546
8547         // Create an initial channel
8548         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8549         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8550         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8551         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8552         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8553
8554         // Move the first channel through the funding flow...
8555         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8556
8557         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8558         check_added_monitors!(nodes[0], 0);
8559
8560         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8561         let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8562         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8563         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8564         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true);
8565 }
8566
8567 #[test]
8568 fn test_htlc_no_detection() {
8569         // This test is a mutation to underscore the detection logic bug we had
8570         // before #653. HTLC value routed is above the remaining balance, thus
8571         // inverting HTLC and `to_remote` output. HTLC will come second and
8572         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8573         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8574         // outputs order detection for correct spending children filtring.
8575
8576         let chanmon_cfgs = create_chanmon_cfgs(2);
8577         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8578         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8579         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8580
8581         // Create some initial channels
8582         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8583
8584         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8585         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8586         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8587         assert_eq!(local_txn[0].input.len(), 1);
8588         assert_eq!(local_txn[0].output.len(), 3);
8589         check_spends!(local_txn[0], chan_1.3);
8590
8591         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8592         let block = create_dummy_block(nodes[0].best_block_hash(), 42, vec![local_txn[0].clone()]);
8593         connect_block(&nodes[0], &block);
8594         // We deliberately connect the local tx twice as this should provoke a failure calling
8595         // this test before #653 fix.
8596         chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &block, nodes[0].best_block_info().1 + 1);
8597         check_closed_broadcast!(nodes[0], true);
8598         check_added_monitors!(nodes[0], 1);
8599         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8600         connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8601
8602         let htlc_timeout = {
8603                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8604                 assert_eq!(node_txn.len(), 1);
8605                 assert_eq!(node_txn[0].input.len(), 1);
8606                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8607                 check_spends!(node_txn[0], local_txn[0]);
8608                 node_txn[0].clone()
8609         };
8610
8611         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![htlc_timeout.clone()]));
8612         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8613         expect_payment_failed!(nodes[0], our_payment_hash, false);
8614 }
8615
8616 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8617         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8618         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8619         // Carol, Alice would be the upstream node, and Carol the downstream.)
8620         //
8621         // Steps of the test:
8622         // 1) Alice sends a HTLC to Carol through Bob.
8623         // 2) Carol doesn't settle the HTLC.
8624         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8625         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8626         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8627         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8628         // 5) Carol release the preimage to Bob off-chain.
8629         // 6) Bob claims the offered output on the broadcasted commitment.
8630         let chanmon_cfgs = create_chanmon_cfgs(3);
8631         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8632         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8633         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8634
8635         // Create some initial channels
8636         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8637         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8638
8639         // Steps (1) and (2):
8640         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8641         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8642
8643         // Check that Alice's commitment transaction now contains an output for this HTLC.
8644         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8645         check_spends!(alice_txn[0], chan_ab.3);
8646         assert_eq!(alice_txn[0].output.len(), 2);
8647         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8648         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8649         assert_eq!(alice_txn.len(), 2);
8650
8651         // Steps (3) and (4):
8652         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8653         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8654         let mut force_closing_node = 0; // Alice force-closes
8655         let mut counterparty_node = 1; // Bob if Alice force-closes
8656
8657         // Bob force-closes
8658         if !broadcast_alice {
8659                 force_closing_node = 1;
8660                 counterparty_node = 0;
8661         }
8662         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8663         check_closed_broadcast!(nodes[force_closing_node], true);
8664         check_added_monitors!(nodes[force_closing_node], 1);
8665         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8666         if go_onchain_before_fulfill {
8667                 let txn_to_broadcast = match broadcast_alice {
8668                         true => alice_txn.clone(),
8669                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8670                 };
8671                 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8672                 if broadcast_alice {
8673                         check_closed_broadcast!(nodes[1], true);
8674                         check_added_monitors!(nodes[1], 1);
8675                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8676                 }
8677         }
8678
8679         // Step (5):
8680         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8681         // process of removing the HTLC from their commitment transactions.
8682         nodes[2].node.claim_funds(payment_preimage);
8683         check_added_monitors!(nodes[2], 1);
8684         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8685
8686         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8687         assert!(carol_updates.update_add_htlcs.is_empty());
8688         assert!(carol_updates.update_fail_htlcs.is_empty());
8689         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8690         assert!(carol_updates.update_fee.is_none());
8691         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8692
8693         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8694         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8695         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8696         if !go_onchain_before_fulfill && broadcast_alice {
8697                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8698                 assert_eq!(events.len(), 1);
8699                 match events[0] {
8700                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8701                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8702                         },
8703                         _ => panic!("Unexpected event"),
8704                 };
8705         }
8706         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8707         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8708         // Carol<->Bob's updated commitment transaction info.
8709         check_added_monitors!(nodes[1], 2);
8710
8711         let events = nodes[1].node.get_and_clear_pending_msg_events();
8712         assert_eq!(events.len(), 2);
8713         let bob_revocation = match events[0] {
8714                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8715                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8716                         (*msg).clone()
8717                 },
8718                 _ => panic!("Unexpected event"),
8719         };
8720         let bob_updates = match events[1] {
8721                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8722                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8723                         (*updates).clone()
8724                 },
8725                 _ => panic!("Unexpected event"),
8726         };
8727
8728         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8729         check_added_monitors!(nodes[2], 1);
8730         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8731         check_added_monitors!(nodes[2], 1);
8732
8733         let events = nodes[2].node.get_and_clear_pending_msg_events();
8734         assert_eq!(events.len(), 1);
8735         let carol_revocation = match events[0] {
8736                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8737                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8738                         (*msg).clone()
8739                 },
8740                 _ => panic!("Unexpected event"),
8741         };
8742         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8743         check_added_monitors!(nodes[1], 1);
8744
8745         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8746         // here's where we put said channel's commitment tx on-chain.
8747         let mut txn_to_broadcast = alice_txn.clone();
8748         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8749         if !go_onchain_before_fulfill {
8750                 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8751                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8752                 if broadcast_alice {
8753                         check_closed_broadcast!(nodes[1], true);
8754                         check_added_monitors!(nodes[1], 1);
8755                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8756                 }
8757                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8758                 if broadcast_alice {
8759                         assert_eq!(bob_txn.len(), 1);
8760                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8761                 } else {
8762                         assert_eq!(bob_txn.len(), 2);
8763                         check_spends!(bob_txn[0], chan_ab.3);
8764                 }
8765         }
8766
8767         // Step (6):
8768         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8769         // broadcasted commitment transaction.
8770         {
8771                 let script_weight = match broadcast_alice {
8772                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8773                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8774                 };
8775                 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8776                 // Bob force-closed and broadcasts the commitment transaction along with a
8777                 // HTLC-output-claiming transaction.
8778                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8779                 if broadcast_alice {
8780                         assert_eq!(bob_txn.len(), 1);
8781                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8782                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8783                 } else {
8784                         assert_eq!(bob_txn.len(), 2);
8785                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8786                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8787                 }
8788         }
8789 }
8790
8791 #[test]
8792 fn test_onchain_htlc_settlement_after_close() {
8793         do_test_onchain_htlc_settlement_after_close(true, true);
8794         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8795         do_test_onchain_htlc_settlement_after_close(true, false);
8796         do_test_onchain_htlc_settlement_after_close(false, false);
8797 }
8798
8799 #[test]
8800 fn test_duplicate_temporary_channel_id_from_different_peers() {
8801         // Tests that we can accept two different `OpenChannel` requests with the same
8802         // `temporary_channel_id`, as long as they are from different peers.
8803         let chanmon_cfgs = create_chanmon_cfgs(3);
8804         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8805         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8806         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8807
8808         // Create an first channel channel
8809         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8810         let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8811
8812         // Create an second channel
8813         nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8814         let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8815
8816         // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8817         // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8818         open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8819
8820         // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8821         // `temporary_channel_id` as they are from different peers.
8822         nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8823         {
8824                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8825                 assert_eq!(events.len(), 1);
8826                 match &events[0] {
8827                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8828                                 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8829                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8830                         },
8831                         _ => panic!("Unexpected event"),
8832                 }
8833         }
8834
8835         nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8836         {
8837                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8838                 assert_eq!(events.len(), 1);
8839                 match &events[0] {
8840                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8841                                 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8842                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8843                         },
8844                         _ => panic!("Unexpected event"),
8845                 }
8846         }
8847 }
8848
8849 #[test]
8850 fn test_duplicate_chan_id() {
8851         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8852         // already open we reject it and keep the old channel.
8853         //
8854         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8855         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8856         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8857         // updating logic for the existing channel.
8858         let chanmon_cfgs = create_chanmon_cfgs(2);
8859         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8860         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8861         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8862
8863         // Create an initial channel
8864         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8865         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8866         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8867         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()));
8868
8869         // Try to create a second channel with the same temporary_channel_id as the first and check
8870         // that it is rejected.
8871         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8872         {
8873                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8874                 assert_eq!(events.len(), 1);
8875                 match events[0] {
8876                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8877                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8878                                 // first (valid) and second (invalid) channels are closed, given they both have
8879                                 // the same non-temporary channel_id. However, currently we do not, so we just
8880                                 // move forward with it.
8881                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8882                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8883                         },
8884                         _ => panic!("Unexpected event"),
8885                 }
8886         }
8887
8888         // Move the first channel through the funding flow...
8889         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8890
8891         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8892         check_added_monitors!(nodes[0], 0);
8893
8894         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8895         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8896         {
8897                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8898                 assert_eq!(added_monitors.len(), 1);
8899                 assert_eq!(added_monitors[0].0, funding_output);
8900                 added_monitors.clear();
8901         }
8902         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
8903
8904         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8905
8906         let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8907         let channel_id = funding_outpoint.to_channel_id();
8908
8909         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8910         // temporary one).
8911
8912         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8913         // Technically this is allowed by the spec, but we don't support it and there's little reason
8914         // to. Still, it shouldn't cause any other issues.
8915         open_chan_msg.temporary_channel_id = channel_id;
8916         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8917         {
8918                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8919                 assert_eq!(events.len(), 1);
8920                 match events[0] {
8921                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8922                                 // Technically, at this point, nodes[1] would be justified in thinking both
8923                                 // channels are closed, but currently we do not, so we just move forward with it.
8924                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8925                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8926                         },
8927                         _ => panic!("Unexpected event"),
8928                 }
8929         }
8930
8931         // Now try to create a second channel which has a duplicate funding output.
8932         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8933         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8934         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
8935         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()));
8936         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8937
8938         let funding_created = {
8939                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8940                 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
8941                 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
8942                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8943                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8944                 // channelmanager in a possibly nonsense state instead).
8945                 let mut as_chan = a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8946                 let logger = test_utils::TestLogger::new();
8947                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8948         };
8949         check_added_monitors!(nodes[0], 0);
8950         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8951         // At this point we'll look up if the channel_id is present and immediately fail the channel
8952         // without trying to persist the `ChannelMonitor`.
8953         check_added_monitors!(nodes[1], 0);
8954
8955         // ...still, nodes[1] will reject the duplicate channel.
8956         {
8957                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8958                 assert_eq!(events.len(), 1);
8959                 match events[0] {
8960                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8961                                 // Technically, at this point, nodes[1] would be justified in thinking both
8962                                 // channels are closed, but currently we do not, so we just move forward with it.
8963                                 assert_eq!(msg.channel_id, channel_id);
8964                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8965                         },
8966                         _ => panic!("Unexpected event"),
8967                 }
8968         }
8969
8970         // finally, finish creating the original channel and send a payment over it to make sure
8971         // everything is functional.
8972         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8973         {
8974                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8975                 assert_eq!(added_monitors.len(), 1);
8976                 assert_eq!(added_monitors[0].0, funding_output);
8977                 added_monitors.clear();
8978         }
8979         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
8980
8981         let events_4 = nodes[0].node.get_and_clear_pending_events();
8982         assert_eq!(events_4.len(), 0);
8983         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8984         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8985
8986         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8987         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
8988         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8989
8990         send_payment(&nodes[0], &[&nodes[1]], 8000000);
8991 }
8992
8993 #[test]
8994 fn test_error_chans_closed() {
8995         // Test that we properly handle error messages, closing appropriate channels.
8996         //
8997         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8998         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8999         // we can test various edge cases around it to ensure we don't regress.
9000         let chanmon_cfgs = create_chanmon_cfgs(3);
9001         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9002         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9003         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9004
9005         // Create some initial channels
9006         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9007         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9008         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
9009
9010         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9011         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9012         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9013
9014         // Closing a channel from a different peer has no effect
9015         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9016         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9017
9018         // Closing one channel doesn't impact others
9019         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9020         check_added_monitors!(nodes[0], 1);
9021         check_closed_broadcast!(nodes[0], false);
9022         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
9023         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9024         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9025         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);
9026         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);
9027
9028         // A null channel ID should close all channels
9029         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9030         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9031         check_added_monitors!(nodes[0], 2);
9032         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
9033         let events = nodes[0].node.get_and_clear_pending_msg_events();
9034         assert_eq!(events.len(), 2);
9035         match events[0] {
9036                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9037                         assert_eq!(msg.contents.flags & 2, 2);
9038                 },
9039                 _ => panic!("Unexpected event"),
9040         }
9041         match events[1] {
9042                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9043                         assert_eq!(msg.contents.flags & 2, 2);
9044                 },
9045                 _ => panic!("Unexpected event"),
9046         }
9047         // Note that at this point users of a standard PeerHandler will end up calling
9048         // peer_disconnected.
9049         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9050         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9051
9052         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9053         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9054         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9055 }
9056
9057 #[test]
9058 fn test_invalid_funding_tx() {
9059         // Test that we properly handle invalid funding transactions sent to us from a peer.
9060         //
9061         // Previously, all other major lightning implementations had failed to properly sanitize
9062         // funding transactions from their counterparties, leading to a multi-implementation critical
9063         // security vulnerability (though we always sanitized properly, we've previously had
9064         // un-released crashes in the sanitization process).
9065         //
9066         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9067         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9068         // gave up on it. We test this here by generating such a transaction.
9069         let chanmon_cfgs = create_chanmon_cfgs(2);
9070         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9071         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9072         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9073
9074         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9075         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()));
9076         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()));
9077
9078         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9079
9080         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9081         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9082         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9083         // its length.
9084         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9085         let wit_program_script: Script = wit_program.into();
9086         for output in tx.output.iter_mut() {
9087                 // Make the confirmed funding transaction have a bogus script_pubkey
9088                 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9089         }
9090
9091         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9092         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()));
9093         check_added_monitors!(nodes[1], 1);
9094         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9095
9096         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()));
9097         check_added_monitors!(nodes[0], 1);
9098         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9099
9100         let events_1 = nodes[0].node.get_and_clear_pending_events();
9101         assert_eq!(events_1.len(), 0);
9102
9103         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9104         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9105         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9106
9107         let expected_err = "funding tx had wrong script/value or output index";
9108         confirm_transaction_at(&nodes[1], &tx, 1);
9109         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9110         check_added_monitors!(nodes[1], 1);
9111         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9112         assert_eq!(events_2.len(), 1);
9113         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9114                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9115                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9116                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9117                 } else { panic!(); }
9118         } else { panic!(); }
9119         assert_eq!(nodes[1].node.list_channels().len(), 0);
9120
9121         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9122         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9123         // as its not 32 bytes long.
9124         let mut spend_tx = Transaction {
9125                 version: 2i32, lock_time: PackedLockTime::ZERO,
9126                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9127                         previous_output: BitcoinOutPoint {
9128                                 txid: tx.txid(),
9129                                 vout: idx as u32,
9130                         },
9131                         script_sig: Script::new(),
9132                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9133                         witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9134                 }).collect(),
9135                 output: vec![TxOut {
9136                         value: 1000,
9137                         script_pubkey: Script::new(),
9138                 }]
9139         };
9140         check_spends!(spend_tx, tx);
9141         mine_transaction(&nodes[1], &spend_tx);
9142 }
9143
9144 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9145         // In the first version of the chain::Confirm interface, after a refactor was made to not
9146         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9147         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9148         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9149         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9150         // spending transaction until height N+1 (or greater). This was due to the way
9151         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9152         // spending transaction at the height the input transaction was confirmed at, not whether we
9153         // should broadcast a spending transaction at the current height.
9154         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9155         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9156         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9157         // until we learned about an additional block.
9158         //
9159         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9160         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9161         let chanmon_cfgs = create_chanmon_cfgs(3);
9162         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9163         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9164         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9165         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9166
9167         create_announced_chan_between_nodes(&nodes, 0, 1);
9168         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9169         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9170         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9171         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9172
9173         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9174         check_closed_broadcast!(nodes[1], true);
9175         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9176         check_added_monitors!(nodes[1], 1);
9177         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9178         assert_eq!(node_txn.len(), 1);
9179
9180         let conf_height = nodes[1].best_block_info().1;
9181         if !test_height_before_timelock {
9182                 connect_blocks(&nodes[1], 24 * 6);
9183         }
9184         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9185                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9186         if test_height_before_timelock {
9187                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9188                 // generate any events or broadcast any transactions
9189                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9190                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9191         } else {
9192                 // We should broadcast an HTLC transaction spending our funding transaction first
9193                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9194                 assert_eq!(spending_txn.len(), 2);
9195                 assert_eq!(spending_txn[0].txid(), node_txn[0].txid());
9196                 check_spends!(spending_txn[1], node_txn[0]);
9197                 // We should also generate a SpendableOutputs event with the to_self output (as its
9198                 // timelock is up).
9199                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9200                 assert_eq!(descriptor_spend_txn.len(), 1);
9201
9202                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9203                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9204                 // additional block built on top of the current chain.
9205                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9206                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9207                 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 }]);
9208                 check_added_monitors!(nodes[1], 1);
9209
9210                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9211                 assert!(updates.update_add_htlcs.is_empty());
9212                 assert!(updates.update_fulfill_htlcs.is_empty());
9213                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9214                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9215                 assert!(updates.update_fee.is_none());
9216                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9217                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9218                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9219         }
9220 }
9221
9222 #[test]
9223 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9224         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9225         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9226 }
9227
9228 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9229         let chanmon_cfgs = create_chanmon_cfgs(2);
9230         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9231         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9232         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9233
9234         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9235
9236         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9237                 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
9238         let route = get_route!(nodes[0], payment_params, 10_000).unwrap();
9239
9240         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9241
9242         {
9243                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9244                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9245                 check_added_monitors!(nodes[0], 1);
9246                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9247                 assert_eq!(events.len(), 1);
9248                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9249                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9250                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9251         }
9252         expect_pending_htlcs_forwardable!(nodes[1]);
9253         expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9254
9255         {
9256                 // Note that we use a different PaymentId here to allow us to duplicativly pay
9257                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9258                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9259                 check_added_monitors!(nodes[0], 1);
9260                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9261                 assert_eq!(events.len(), 1);
9262                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9263                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9264                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9265                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9266                 // assume the second is a privacy attack (no longer particularly relevant
9267                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9268                 // the first HTLC delivered above.
9269         }
9270
9271         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9272         nodes[1].node.process_pending_htlc_forwards();
9273
9274         if test_for_second_fail_panic {
9275                 // Now we go fail back the first HTLC from the user end.
9276                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9277
9278                 let expected_destinations = vec![
9279                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9280                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9281                 ];
9282                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],  expected_destinations);
9283                 nodes[1].node.process_pending_htlc_forwards();
9284
9285                 check_added_monitors!(nodes[1], 1);
9286                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9287                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9288
9289                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9290                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9291                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9292
9293                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9294                 assert_eq!(failure_events.len(), 4);
9295                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9296                 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9297                 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9298                 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9299         } else {
9300                 // Let the second HTLC fail and claim the first
9301                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9302                 nodes[1].node.process_pending_htlc_forwards();
9303
9304                 check_added_monitors!(nodes[1], 1);
9305                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9306                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9307                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9308
9309                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9310
9311                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9312         }
9313 }
9314
9315 #[test]
9316 fn test_dup_htlc_second_fail_panic() {
9317         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9318         // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9319         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9320         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9321         do_test_dup_htlc_second_rejected(true);
9322 }
9323
9324 #[test]
9325 fn test_dup_htlc_second_rejected() {
9326         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9327         // simply reject the second HTLC but are still able to claim the first HTLC.
9328         do_test_dup_htlc_second_rejected(false);
9329 }
9330
9331 #[test]
9332 fn test_inconsistent_mpp_params() {
9333         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9334         // such HTLC and allow the second to stay.
9335         let chanmon_cfgs = create_chanmon_cfgs(4);
9336         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9337         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9338         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9339
9340         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9341         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9342         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9343         let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9344
9345         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9346                 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
9347         let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
9348         assert_eq!(route.paths.len(), 2);
9349         route.paths.sort_by(|path_a, _| {
9350                 // Sort the path so that the path through nodes[1] comes first
9351                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9352                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9353         });
9354
9355         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9356
9357         let cur_height = nodes[0].best_block_info().1;
9358         let payment_id = PaymentId([42; 32]);
9359
9360         let session_privs = {
9361                 // We create a fake route here so that we start with three pending HTLCs, which we'll
9362                 // ultimately have, just not right away.
9363                 let mut dup_route = route.clone();
9364                 dup_route.paths.push(route.paths[1].clone());
9365                 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9366                         RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9367         };
9368         nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9369                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9370                 &None, session_privs[0]).unwrap();
9371         check_added_monitors!(nodes[0], 1);
9372
9373         {
9374                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9375                 assert_eq!(events.len(), 1);
9376                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9377         }
9378         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9379
9380         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9381                 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9382         check_added_monitors!(nodes[0], 1);
9383
9384         {
9385                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9386                 assert_eq!(events.len(), 1);
9387                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9388
9389                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9390                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9391
9392                 expect_pending_htlcs_forwardable!(nodes[2]);
9393                 check_added_monitors!(nodes[2], 1);
9394
9395                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9396                 assert_eq!(events.len(), 1);
9397                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9398
9399                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9400                 check_added_monitors!(nodes[3], 0);
9401                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9402
9403                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9404                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9405                 // post-payment_secrets) and fail back the new HTLC.
9406         }
9407         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9408         nodes[3].node.process_pending_htlc_forwards();
9409         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9410         nodes[3].node.process_pending_htlc_forwards();
9411
9412         check_added_monitors!(nodes[3], 1);
9413
9414         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9415         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9416         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9417
9418         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 }]);
9419         check_added_monitors!(nodes[2], 1);
9420
9421         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9422         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9423         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9424
9425         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9426
9427         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9428                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9429                 &None, session_privs[2]).unwrap();
9430         check_added_monitors!(nodes[0], 1);
9431
9432         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9433         assert_eq!(events.len(), 1);
9434         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9435
9436         do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9437         expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true);
9438 }
9439
9440 #[test]
9441 fn test_keysend_payments_to_public_node() {
9442         let chanmon_cfgs = create_chanmon_cfgs(2);
9443         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9444         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9445         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9446
9447         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9448         let network_graph = nodes[0].network_graph.clone();
9449         let payer_pubkey = nodes[0].node.get_our_node_id();
9450         let payee_pubkey = nodes[1].node.get_our_node_id();
9451         let route_params = RouteParameters {
9452                 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9453                 final_value_msat: 10000,
9454         };
9455         let scorer = test_utils::TestScorer::new();
9456         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9457         let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
9458
9459         let test_preimage = PaymentPreimage([42; 32]);
9460         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
9461                 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
9462         check_added_monitors!(nodes[0], 1);
9463         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9464         assert_eq!(events.len(), 1);
9465         let event = events.pop().unwrap();
9466         let path = vec![&nodes[1]];
9467         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9468         claim_payment(&nodes[0], &path, test_preimage);
9469 }
9470
9471 #[test]
9472 fn test_keysend_payments_to_private_node() {
9473         let chanmon_cfgs = create_chanmon_cfgs(2);
9474         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9475         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9476         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9477
9478         let payer_pubkey = nodes[0].node.get_our_node_id();
9479         let payee_pubkey = nodes[1].node.get_our_node_id();
9480
9481         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
9482         let route_params = RouteParameters {
9483                 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9484                 final_value_msat: 10000,
9485         };
9486         let network_graph = nodes[0].network_graph.clone();
9487         let first_hops = nodes[0].node.list_usable_channels();
9488         let scorer = test_utils::TestScorer::new();
9489         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9490         let route = find_route(
9491                 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9492                 nodes[0].logger, &scorer, &(), &random_seed_bytes
9493         ).unwrap();
9494
9495         let test_preimage = PaymentPreimage([42; 32]);
9496         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
9497                 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
9498         check_added_monitors!(nodes[0], 1);
9499         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9500         assert_eq!(events.len(), 1);
9501         let event = events.pop().unwrap();
9502         let path = vec![&nodes[1]];
9503         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9504         claim_payment(&nodes[0], &path, test_preimage);
9505 }
9506
9507 #[test]
9508 fn test_double_partial_claim() {
9509         // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9510         // time out, the sender resends only some of the MPP parts, then the user processes the
9511         // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9512         // amount.
9513         let chanmon_cfgs = create_chanmon_cfgs(4);
9514         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9515         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9516         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9517
9518         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9519         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9520         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9521         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9522
9523         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9524         assert_eq!(route.paths.len(), 2);
9525         route.paths.sort_by(|path_a, _| {
9526                 // Sort the path so that the path through nodes[1] comes first
9527                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9528                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9529         });
9530
9531         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9532         // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9533         // amount of time to respond to.
9534
9535         // Connect some blocks to time out the payment
9536         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9537         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9538
9539         let failed_destinations = vec![
9540                 HTLCDestination::FailedPayment { payment_hash },
9541                 HTLCDestination::FailedPayment { payment_hash },
9542         ];
9543         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9544
9545         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9546
9547         // nodes[1] now retries one of the two paths...
9548         nodes[0].node.send_payment_with_route(&route, payment_hash,
9549                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9550         check_added_monitors!(nodes[0], 2);
9551
9552         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9553         assert_eq!(events.len(), 2);
9554         let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9555         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9556
9557         // At this point nodes[3] has received one half of the payment, and the user goes to handle
9558         // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9559         nodes[3].node.claim_funds(payment_preimage);
9560         check_added_monitors!(nodes[3], 0);
9561         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9562 }
9563
9564 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9565 #[derive(Clone, Copy, PartialEq)]
9566 enum ExposureEvent {
9567         /// Breach occurs at HTLC forwarding (see `send_htlc`)
9568         AtHTLCForward,
9569         /// Breach occurs at HTLC reception (see `update_add_htlc`)
9570         AtHTLCReception,
9571         /// Breach occurs at outbound update_fee (see `send_update_fee`)
9572         AtUpdateFeeOutbound,
9573 }
9574
9575 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9576         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9577         // policy.
9578         //
9579         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9580         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9581         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9582         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9583         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9584         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9585         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9586         // might be available again for HTLC processing once the dust bandwidth has cleared up.
9587
9588         let chanmon_cfgs = create_chanmon_cfgs(2);
9589         let mut config = test_default_channel_config();
9590         config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9591         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9592         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9593         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9594
9595         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9596         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9597         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9598         open_channel.max_accepted_htlcs = 60;
9599         if on_holder_tx {
9600                 open_channel.dust_limit_satoshis = 546;
9601         }
9602         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9603         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9604         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9605
9606         let opt_anchors = false;
9607
9608         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9609
9610         if on_holder_tx {
9611                 let mut node_0_per_peer_lock;
9612                 let mut node_0_peer_state_lock;
9613                 let mut chan = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id);
9614                 chan.holder_dust_limit_satoshis = 546;
9615         }
9616
9617         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9618         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()));
9619         check_added_monitors!(nodes[1], 1);
9620         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9621
9622         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()));
9623         check_added_monitors!(nodes[0], 1);
9624         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9625
9626         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9627         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9628         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9629
9630         let dust_buffer_feerate = {
9631                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9632                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9633                 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9634                 chan.get_dust_buffer_feerate(None) as u64
9635         };
9636         let dust_outbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * htlc_timeout_tx_weight(opt_anchors) / 1000 + open_channel.dust_limit_satoshis - 1) * 1000;
9637         let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9638
9639         let dust_inbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * htlc_success_tx_weight(opt_anchors) / 1000 + open_channel.dust_limit_satoshis - 1) * 1000;
9640         let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9641
9642         let dust_htlc_on_counterparty_tx: u64 = 25;
9643         let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9644
9645         if on_holder_tx {
9646                 if dust_outbound_balance {
9647                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9648                         // Outbound dust balance: 4372 sats
9649                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9650                         for _ in 0..dust_outbound_htlc_on_holder_tx {
9651                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9652                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9653                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9654                         }
9655                 } else {
9656                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9657                         // Inbound dust balance: 4372 sats
9658                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9659                         for _ in 0..dust_inbound_htlc_on_holder_tx {
9660                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9661                         }
9662                 }
9663         } else {
9664                 if dust_outbound_balance {
9665                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9666                         // Outbound dust balance: 5000 sats
9667                         for _ in 0..dust_htlc_on_counterparty_tx {
9668                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9669                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9670                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9671                         }
9672                 } else {
9673                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9674                         // Inbound dust balance: 5000 sats
9675                         for _ in 0..dust_htlc_on_counterparty_tx {
9676                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9677                         }
9678                 }
9679         }
9680
9681         let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9682         if exposure_breach_event == ExposureEvent::AtHTLCForward {
9683                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat });
9684                 let mut config = UserConfig::default();
9685                 // With default dust exposure: 5000 sats
9686                 if on_holder_tx {
9687                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9688                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9689                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9690                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9691                                 ), true, APIError::ChannelUnavailable { ref err },
9692                                 assert_eq!(err, &format!("Cannot send value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", if dust_outbound_balance { dust_outbound_overflow } else { dust_inbound_overflow }, config.channel_config.max_dust_htlc_exposure_msat)));
9693                 } else {
9694                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9695                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9696                                 ), true, APIError::ChannelUnavailable { ref err },
9697                                 assert_eq!(err, &format!("Cannot send value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx", dust_overflow, config.channel_config.max_dust_htlc_exposure_msat)));
9698                 }
9699         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9700                 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 });
9701                 nodes[1].node.send_payment_with_route(&route, payment_hash,
9702                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9703                 check_added_monitors!(nodes[1], 1);
9704                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9705                 assert_eq!(events.len(), 1);
9706                 let payment_event = SendEvent::from_event(events.remove(0));
9707                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9708                 // With default dust exposure: 5000 sats
9709                 if on_holder_tx {
9710                         // Outbound dust balance: 6399 sats
9711                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9712                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9713                         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", if dust_outbound_balance { dust_outbound_overflow } else { dust_inbound_overflow }, config.channel_config.max_dust_htlc_exposure_msat), 1);
9714                 } else {
9715                         // Outbound dust balance: 5200 sats
9716                         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx", dust_overflow, config.channel_config.max_dust_htlc_exposure_msat), 1);
9717                 }
9718         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9719                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
9720                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9721                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9722                 {
9723                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9724                         *feerate_lock = *feerate_lock * 10;
9725                 }
9726                 nodes[0].node.timer_tick_occurred();
9727                 check_added_monitors!(nodes[0], 1);
9728                 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9729         }
9730
9731         let _ = nodes[0].node.get_and_clear_pending_msg_events();
9732         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9733         added_monitors.clear();
9734 }
9735
9736 #[test]
9737 fn test_max_dust_htlc_exposure() {
9738         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9739         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9740         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9741         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9742         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9743         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9744         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9745         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9746         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9747         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9748         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9749         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
9750 }
9751
9752 #[test]
9753 fn test_non_final_funding_tx() {
9754         let chanmon_cfgs = create_chanmon_cfgs(2);
9755         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9756         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9757         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9758
9759         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9760         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9761         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9762         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9763         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9764
9765         let best_height = nodes[0].node.best_block.read().unwrap().height();
9766
9767         let chan_id = *nodes[0].network_chan_count.borrow();
9768         let events = nodes[0].node.get_and_clear_pending_events();
9769         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9770         assert_eq!(events.len(), 1);
9771         let mut tx = match events[0] {
9772                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9773                         // Timelock the transaction _beyond_ the best client height + 1.
9774                         Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 2), input: vec![input], output: vec![TxOut {
9775                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9776                         }]}
9777                 },
9778                 _ => panic!("Unexpected event"),
9779         };
9780         // Transaction should fail as it's evaluated as non-final for propagation.
9781         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9782                 Err(APIError::APIMisuseError { err }) => {
9783                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9784                 },
9785                 _ => panic!()
9786         }
9787
9788         // However, transaction should be accepted if it's in a +1 headroom from best block.
9789         tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9790         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9791         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9792 }
9793
9794 #[test]
9795 fn accept_busted_but_better_fee() {
9796         // If a peer sends us a fee update that is too low, but higher than our previous channel
9797         // feerate, we should accept it. In the future we may want to consider closing the channel
9798         // later, but for now we only accept the update.
9799         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9800         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9801         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9802         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9803
9804         create_chan_between_nodes(&nodes[0], &nodes[1]);
9805
9806         // Set nodes[1] to expect 5,000 sat/kW.
9807         {
9808                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9809                 *feerate_lock = 5000;
9810         }
9811
9812         // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
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, ref commitment_signed, .. }, .. } => {
9824                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9825                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9826                 },
9827                 _ => panic!("Unexpected event"),
9828         };
9829
9830         // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9831         // it.
9832         {
9833                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9834                 *feerate_lock = 2000;
9835         }
9836         nodes[0].node.timer_tick_occurred();
9837         check_added_monitors!(nodes[0], 1);
9838
9839         let events = nodes[0].node.get_and_clear_pending_msg_events();
9840         assert_eq!(events.len(), 1);
9841         match events[0] {
9842                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9843                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9844                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9845                 },
9846                 _ => panic!("Unexpected event"),
9847         };
9848
9849         // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9850         // channel.
9851         {
9852                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9853                 *feerate_lock = 1000;
9854         }
9855         nodes[0].node.timer_tick_occurred();
9856         check_added_monitors!(nodes[0], 1);
9857
9858         let events = nodes[0].node.get_and_clear_pending_msg_events();
9859         assert_eq!(events.len(), 1);
9860         match events[0] {
9861                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9862                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9863                         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9864                                 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() });
9865                         check_closed_broadcast!(nodes[1], true);
9866                         check_added_monitors!(nodes[1], 1);
9867                 },
9868                 _ => panic!("Unexpected event"),
9869         };
9870 }
9871
9872 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9873         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9874         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9875         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9876         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9877         let min_final_cltv_expiry_delta = 120;
9878         let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9879                 min_final_cltv_expiry_delta - 2 };
9880         let recv_value = 100_000;
9881
9882         create_chan_between_nodes(&nodes[0], &nodes[1]);
9883
9884         let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
9885         let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
9886                 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
9887                         Some(recv_value), Some(min_final_cltv_expiry_delta));
9888                 (payment_hash, payment_preimage, payment_secret)
9889         } else {
9890                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
9891                 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
9892         };
9893         let route = get_route!(nodes[0], payment_parameters, recv_value).unwrap();
9894         nodes[0].node.send_payment_with_route(&route, payment_hash,
9895                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9896         check_added_monitors!(nodes[0], 1);
9897         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9898         assert_eq!(events.len(), 1);
9899         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9900         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9901         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9902         expect_pending_htlcs_forwardable!(nodes[1]);
9903
9904         if valid_delta {
9905                 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
9906                         None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
9907
9908                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9909         } else {
9910                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9911
9912                 check_added_monitors!(nodes[1], 1);
9913
9914                 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9915                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
9916                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
9917
9918                 expect_payment_failed!(nodes[0], payment_hash, true);
9919         }
9920 }
9921
9922 #[test]
9923 fn test_payment_with_custom_min_cltv_expiry_delta() {
9924         do_payment_with_custom_min_final_cltv_expiry(false, false);
9925         do_payment_with_custom_min_final_cltv_expiry(false, true);
9926         do_payment_with_custom_min_final_cltv_expiry(true, false);
9927         do_payment_with_custom_min_final_cltv_expiry(true, true);
9928 }