]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/ln/functional_tests.rs
af547b3af084ef5f73f0f49080b837624f3f070c
[rust-lightning] / lightning / src / ln / functional_tests.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
13
14 use crate::chain;
15 use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Listen, Watch};
16 use crate::chain::chaininterface::LowerBoundedFeeEstimator;
17 use crate::chain::channelmonitor;
18 use crate::chain::channelmonitor::{CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
19 use crate::chain::transaction::OutPoint;
20 use crate::chain::keysinterface::{ChannelSigner, EcdsaChannelSigner, EntropySource};
21 use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose, ClosureReason, HTLCDestination};
22 use crate::ln::{PaymentPreimage, PaymentSecret, PaymentHash};
23 use crate::ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT};
24 use crate::ln::channelmanager::{self, PaymentId, RAACommitmentOrder, PaymentSendFailure, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA};
25 use crate::ln::channel::{Channel, ChannelError};
26 use crate::ln::{chan_utils, onion_utils};
27 use crate::ln::chan_utils::{OFFERED_HTLC_SCRIPT_WEIGHT, htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
28 use crate::routing::gossip::{NetworkGraph, NetworkUpdate};
29 use crate::routing::router::{PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
30 use crate::ln::features::{ChannelFeatures, NodeFeatures};
31 use crate::ln::msgs;
32 use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
33 use crate::util::enforcing_trait_impls::EnforcingSigner;
34 use crate::util::test_utils;
35 use crate::util::errors::APIError;
36 use crate::util::ser::{Writeable, ReadableArgs};
37 use crate::util::string::UntrustedString;
38 use crate::util::config::UserConfig;
39
40 use bitcoin::hash_types::BlockHash;
41 use bitcoin::blockdata::block::{Block, BlockHeader};
42 use bitcoin::blockdata::script::{Builder, Script};
43 use bitcoin::blockdata::opcodes;
44 use bitcoin::blockdata::constants::genesis_block;
45 use bitcoin::network::constants::Network;
46 use bitcoin::{PackedLockTime, Sequence, Transaction, TxIn, TxMerkleNode, TxOut, Witness};
47 use bitcoin::OutPoint as BitcoinOutPoint;
48
49 use bitcoin::secp256k1::Secp256k1;
50 use bitcoin::secp256k1::{PublicKey,SecretKey};
51
52 use regex;
53
54 use crate::io;
55 use crate::prelude::*;
56 use alloc::collections::BTreeSet;
57 use core::default::Default;
58 use core::iter::repeat;
59 use bitcoin::hashes::Hash;
60 use crate::sync::{Arc, Mutex};
61
62 use crate::ln::functional_test_utils::*;
63 use crate::ln::chan_utils::CommitmentTransaction;
64
65 #[test]
66 fn test_insane_channel_opens() {
67         // Stand up a network of 2 nodes
68         use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
69         let mut cfg = UserConfig::default();
70         cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
71         let chanmon_cfgs = create_chanmon_cfgs(2);
72         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
73         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
74         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
75
76         // Instantiate channel parameters where we push the maximum msats given our
77         // funding satoshis
78         let channel_value_sat = 31337; // same as funding satoshis
79         let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
80         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
81
82         // Have node0 initiate a channel to node1 with aforementioned parameters
83         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
84
85         // Extract the channel open message from node0 to node1
86         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
87
88         // Test helper that asserts we get the correct error string given a mutator
89         // that supposedly makes the channel open message insane
90         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
91                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &message_mutator(open_channel_message.clone()));
92                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
93                 assert_eq!(msg_events.len(), 1);
94                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
95                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
96                         match action {
97                                 &ErrorAction::SendErrorMessage { .. } => {
98                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager", expected_regex, 1);
99                                 },
100                                 _ => panic!("unexpected event!"),
101                         }
102                 } else { assert!(false); }
103         };
104
105         use crate::ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
106
107         // Test all mutations that would make the channel open message insane
108         insane_open_helper(format!("Per our config, funding must be at most {}. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1, TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2; msg });
109         insane_open_helper(format!("Funding must be smaller than the total bitcoin supply. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS; msg });
110
111         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
112
113         insane_open_helper(r"push_msat \d+ was larger than channel amount minus reserve \(\d+\)", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
114
115         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
116
117         insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
118
119         insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
120
121         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
122
123         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
124 }
125
126 #[test]
127 fn test_funding_exceeds_no_wumbo_limit() {
128         // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
129         // them.
130         use crate::ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
131         let chanmon_cfgs = create_chanmon_cfgs(2);
132         let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
133         *node_cfgs[1].override_init_features.borrow_mut() = Some(channelmanager::provided_init_features(&test_default_channel_config()).clear_wumbo());
134         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
135         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
136
137         match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
138                 Err(APIError::APIMisuseError { err }) => {
139                         assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
140                 },
141                 _ => panic!()
142         }
143 }
144
145 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
146         // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
147         // but only for them. Because some LSPs do it with some level of trust of the clients (for a
148         // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
149         // in normal testing, we test it explicitly here.
150         let chanmon_cfgs = create_chanmon_cfgs(2);
151         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
152         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
153         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
154         let default_config = UserConfig::default();
155
156         // Have node0 initiate a channel to node1 with aforementioned parameters
157         let mut push_amt = 100_000_000;
158         let feerate_per_kw = 253;
159         let opt_anchors = false;
160         push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
161         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
162
163         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, if send_from_initiator { 0 } else { push_amt }, 42, None).unwrap();
164         let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
165         if !send_from_initiator {
166                 open_channel_message.channel_reserve_satoshis = 0;
167                 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
168         }
169         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
170
171         // Extract the channel accept message from node1 to node0
172         let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
173         if send_from_initiator {
174                 accept_channel_message.channel_reserve_satoshis = 0;
175                 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
176         }
177         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
178         {
179                 let sender_node = if send_from_initiator { &nodes[1] } else { &nodes[0] };
180                 let counterparty_node = if send_from_initiator { &nodes[0] } else { &nodes[1] };
181                 let mut sender_node_per_peer_lock;
182                 let mut sender_node_peer_state_lock;
183                 let mut chan = get_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
184                 chan.holder_selected_channel_reserve_satoshis = 0;
185                 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
186         }
187
188         let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
189         let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
190         create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
191
192         // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
193         // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
194         if send_from_initiator {
195                 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
196                         // Note that for outbound channels we have to consider the commitment tx fee and the
197                         // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
198                         // well as an additional HTLC.
199                         - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
200         } else {
201                 send_payment(&nodes[1], &[&nodes[0]], push_amt);
202         }
203 }
204
205 #[test]
206 fn test_counterparty_no_reserve() {
207         do_test_counterparty_no_reserve(true);
208         do_test_counterparty_no_reserve(false);
209 }
210
211 #[test]
212 fn test_async_inbound_update_fee() {
213         let chanmon_cfgs = create_chanmon_cfgs(2);
214         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
215         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
216         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
217         create_announced_chan_between_nodes(&nodes, 0, 1);
218
219         // balancing
220         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
221
222         // A                                        B
223         // update_fee                            ->
224         // send (1) commitment_signed            -.
225         //                                       <- update_add_htlc/commitment_signed
226         // send (2) RAA (awaiting remote revoke) -.
227         // (1) commitment_signed is delivered    ->
228         //                                       .- send (3) RAA (awaiting remote revoke)
229         // (2) RAA is delivered                  ->
230         //                                       .- send (4) commitment_signed
231         //                                       <- (3) RAA is delivered
232         // send (5) commitment_signed            -.
233         //                                       <- (4) commitment_signed is delivered
234         // send (6) RAA                          -.
235         // (5) commitment_signed is delivered    ->
236         //                                       <- RAA
237         // (6) RAA is delivered                  ->
238
239         // First nodes[0] generates an update_fee
240         {
241                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
242                 *feerate_lock += 20;
243         }
244         nodes[0].node.timer_tick_occurred();
245         check_added_monitors!(nodes[0], 1);
246
247         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
248         assert_eq!(events_0.len(), 1);
249         let (update_msg, commitment_signed) = match events_0[0] { // (1)
250                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
251                         (update_fee.as_ref(), commitment_signed)
252                 },
253                 _ => panic!("Unexpected event"),
254         };
255
256         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
257
258         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
259         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
260         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
261         check_added_monitors!(nodes[1], 1);
262
263         let payment_event = {
264                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
265                 assert_eq!(events_1.len(), 1);
266                 SendEvent::from_event(events_1.remove(0))
267         };
268         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
269         assert_eq!(payment_event.msgs.len(), 1);
270
271         // ...now when the messages get delivered everyone should be happy
272         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
273         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
274         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
275         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
276         check_added_monitors!(nodes[0], 1);
277
278         // deliver(1), generate (3):
279         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
280         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
281         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
282         check_added_monitors!(nodes[1], 1);
283
284         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
285         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
286         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
287         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
288         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
289         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
290         assert!(bs_update.update_fee.is_none()); // (4)
291         check_added_monitors!(nodes[1], 1);
292
293         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
294         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
295         assert!(as_update.update_add_htlcs.is_empty()); // (5)
296         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
297         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
298         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
299         assert!(as_update.update_fee.is_none()); // (5)
300         check_added_monitors!(nodes[0], 1);
301
302         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
303         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
304         // only (6) so get_event_msg's assert(len == 1) passes
305         check_added_monitors!(nodes[0], 1);
306
307         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
308         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
309         check_added_monitors!(nodes[1], 1);
310
311         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
312         check_added_monitors!(nodes[0], 1);
313
314         let events_2 = nodes[0].node.get_and_clear_pending_events();
315         assert_eq!(events_2.len(), 1);
316         match events_2[0] {
317                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
318                 _ => panic!("Unexpected event"),
319         }
320
321         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
322         check_added_monitors!(nodes[1], 1);
323 }
324
325 #[test]
326 fn test_update_fee_unordered_raa() {
327         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
328         // crash in an earlier version of the update_fee patch)
329         let chanmon_cfgs = create_chanmon_cfgs(2);
330         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
331         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
332         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
333         create_announced_chan_between_nodes(&nodes, 0, 1);
334
335         // balancing
336         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
337
338         // First nodes[0] generates an update_fee
339         {
340                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
341                 *feerate_lock += 20;
342         }
343         nodes[0].node.timer_tick_occurred();
344         check_added_monitors!(nodes[0], 1);
345
346         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
347         assert_eq!(events_0.len(), 1);
348         let update_msg = match events_0[0] { // (1)
349                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
350                         update_fee.as_ref()
351                 },
352                 _ => panic!("Unexpected event"),
353         };
354
355         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
356
357         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
358         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
359         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
360         check_added_monitors!(nodes[1], 1);
361
362         let payment_event = {
363                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
364                 assert_eq!(events_1.len(), 1);
365                 SendEvent::from_event(events_1.remove(0))
366         };
367         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
368         assert_eq!(payment_event.msgs.len(), 1);
369
370         // ...now when the messages get delivered everyone should be happy
371         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
372         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
373         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
374         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
375         check_added_monitors!(nodes[0], 1);
376
377         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
378         check_added_monitors!(nodes[1], 1);
379
380         // We can't continue, sadly, because our (1) now has a bogus signature
381 }
382
383 #[test]
384 fn test_multi_flight_update_fee() {
385         let chanmon_cfgs = create_chanmon_cfgs(2);
386         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
387         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
388         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
389         create_announced_chan_between_nodes(&nodes, 0, 1);
390
391         // A                                        B
392         // update_fee/commitment_signed          ->
393         //                                       .- send (1) RAA and (2) commitment_signed
394         // update_fee (never committed)          ->
395         // (3) update_fee                        ->
396         // We have to manually generate the above update_fee, it is allowed by the protocol but we
397         // don't track which updates correspond to which revoke_and_ack responses so we're in
398         // AwaitingRAA mode and will not generate the update_fee yet.
399         //                                       <- (1) RAA delivered
400         // (3) is generated and send (4) CS      -.
401         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
402         // know the per_commitment_point to use for it.
403         //                                       <- (2) commitment_signed delivered
404         // revoke_and_ack                        ->
405         //                                          B should send no response here
406         // (4) commitment_signed delivered       ->
407         //                                       <- RAA/commitment_signed delivered
408         // revoke_and_ack                        ->
409
410         // First nodes[0] generates an update_fee
411         let initial_feerate;
412         {
413                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
414                 initial_feerate = *feerate_lock;
415                 *feerate_lock = initial_feerate + 20;
416         }
417         nodes[0].node.timer_tick_occurred();
418         check_added_monitors!(nodes[0], 1);
419
420         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
421         assert_eq!(events_0.len(), 1);
422         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
423                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
424                         (update_fee.as_ref().unwrap(), commitment_signed)
425                 },
426                 _ => panic!("Unexpected event"),
427         };
428
429         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
430         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
431         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
432         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
433         check_added_monitors!(nodes[1], 1);
434
435         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
436         // transaction:
437         {
438                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
439                 *feerate_lock = initial_feerate + 40;
440         }
441         nodes[0].node.timer_tick_occurred();
442         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
443         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
444
445         // Create the (3) update_fee message that nodes[0] will generate before it does...
446         let mut update_msg_2 = msgs::UpdateFee {
447                 channel_id: update_msg_1.channel_id.clone(),
448                 feerate_per_kw: (initial_feerate + 30) as u32,
449         };
450
451         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
452
453         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
454         // Deliver (3)
455         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
456
457         // Deliver (1), generating (3) and (4)
458         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
459         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
460         check_added_monitors!(nodes[0], 1);
461         assert!(as_second_update.update_add_htlcs.is_empty());
462         assert!(as_second_update.update_fulfill_htlcs.is_empty());
463         assert!(as_second_update.update_fail_htlcs.is_empty());
464         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
465         // Check that the update_fee newly generated matches what we delivered:
466         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
467         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
468
469         // Deliver (2) commitment_signed
470         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
471         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
472         check_added_monitors!(nodes[0], 1);
473         // No commitment_signed so get_event_msg's assert(len == 1) passes
474
475         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
476         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
477         check_added_monitors!(nodes[1], 1);
478
479         // Delever (4)
480         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
481         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
482         check_added_monitors!(nodes[1], 1);
483
484         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
485         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
486         check_added_monitors!(nodes[0], 1);
487
488         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
489         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
490         // No commitment_signed so get_event_msg's assert(len == 1) passes
491         check_added_monitors!(nodes[0], 1);
492
493         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
494         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
495         check_added_monitors!(nodes[1], 1);
496 }
497
498 fn do_test_sanity_on_in_flight_opens(steps: u8) {
499         // Previously, we had issues deserializing channels when we hadn't connected the first block
500         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
501         // serialization round-trips and simply do steps towards opening a channel and then drop the
502         // Node objects.
503
504         let chanmon_cfgs = create_chanmon_cfgs(2);
505         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
506         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
507         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
508
509         if steps & 0b1000_0000 != 0{
510                 let block = Block {
511                         header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
512                         txdata: vec![],
513                 };
514                 connect_block(&nodes[0], &block);
515                 connect_block(&nodes[1], &block);
516         }
517
518         if steps & 0x0f == 0 { return; }
519         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
520         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
521
522         if steps & 0x0f == 1 { return; }
523         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
524         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
525
526         if steps & 0x0f == 2 { return; }
527         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
528
529         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
530
531         if steps & 0x0f == 3 { return; }
532         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
533         check_added_monitors!(nodes[0], 0);
534         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
535
536         if steps & 0x0f == 4 { return; }
537         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
538         {
539                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
540                 assert_eq!(added_monitors.len(), 1);
541                 assert_eq!(added_monitors[0].0, funding_output);
542                 added_monitors.clear();
543         }
544         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         let events_4 = nodes[0].node.get_and_clear_pending_events();
556         assert_eq!(events_4.len(), 0);
557
558         if steps & 0x0f == 6 { return; }
559         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
560
561         if steps & 0x0f == 7 { return; }
562         confirm_transaction_at(&nodes[0], &tx, 2);
563         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
564         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
565         expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
566 }
567
568 #[test]
569 fn test_sanity_on_in_flight_opens() {
570         do_test_sanity_on_in_flight_opens(0);
571         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
572         do_test_sanity_on_in_flight_opens(1);
573         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
574         do_test_sanity_on_in_flight_opens(2);
575         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
576         do_test_sanity_on_in_flight_opens(3);
577         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
578         do_test_sanity_on_in_flight_opens(4);
579         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
580         do_test_sanity_on_in_flight_opens(5);
581         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
582         do_test_sanity_on_in_flight_opens(6);
583         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
584         do_test_sanity_on_in_flight_opens(7);
585         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
586         do_test_sanity_on_in_flight_opens(8);
587         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
588 }
589
590 #[test]
591 fn test_update_fee_vanilla() {
592         let chanmon_cfgs = create_chanmon_cfgs(2);
593         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
594         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
595         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
596         create_announced_chan_between_nodes(&nodes, 0, 1);
597
598         {
599                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
600                 *feerate_lock += 25;
601         }
602         nodes[0].node.timer_tick_occurred();
603         check_added_monitors!(nodes[0], 1);
604
605         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
606         assert_eq!(events_0.len(), 1);
607         let (update_msg, commitment_signed) = match events_0[0] {
608                         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 } } => {
609                         (update_fee.as_ref(), commitment_signed)
610                 },
611                 _ => panic!("Unexpected event"),
612         };
613         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
614
615         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
616         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
617         check_added_monitors!(nodes[1], 1);
618
619         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
620         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
621         check_added_monitors!(nodes[0], 1);
622
623         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
624         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
625         // No commitment_signed so get_event_msg's assert(len == 1) passes
626         check_added_monitors!(nodes[0], 1);
627
628         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
629         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
630         check_added_monitors!(nodes[1], 1);
631 }
632
633 #[test]
634 fn test_update_fee_that_funder_cannot_afford() {
635         let chanmon_cfgs = create_chanmon_cfgs(2);
636         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
637         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
638         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
639         let channel_value = 5000;
640         let push_sats = 700;
641         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000);
642         let channel_id = chan.2;
643         let secp_ctx = Secp256k1::new();
644         let default_config = UserConfig::default();
645         let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
646
647         let opt_anchors = false;
648
649         // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
650         // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
651         // calculate two different feerates here - the expected local limit as well as the expected
652         // remote limit.
653         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;
654         let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
655         {
656                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
657                 *feerate_lock = feerate;
658         }
659         nodes[0].node.timer_tick_occurred();
660         check_added_monitors!(nodes[0], 1);
661         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
662
663         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
664
665         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
666
667         // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
668         {
669                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
670
671                 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
672                 assert_eq!(commitment_tx.output.len(), 2);
673                 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
674                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
675                 actual_fee = channel_value - actual_fee;
676                 assert_eq!(total_fee, actual_fee);
677         }
678
679         {
680                 // Increment the feerate by a small constant, accounting for rounding errors
681                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
682                 *feerate_lock += 4;
683         }
684         nodes[0].node.timer_tick_occurred();
685         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
686         check_added_monitors!(nodes[0], 0);
687
688         const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
689
690         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
691         // needed to sign the new commitment tx and (2) sign the new commitment tx.
692         let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
693                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
694                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
695                 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
696                 let chan_signer = local_chan.get_signer();
697                 let pubkeys = chan_signer.pubkeys();
698                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
699                  pubkeys.funding_pubkey)
700         };
701         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
702                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
703                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
704                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
705                 let chan_signer = remote_chan.get_signer();
706                 let pubkeys = chan_signer.pubkeys();
707                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
708                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
709                  pubkeys.funding_pubkey)
710         };
711
712         // Assemble the set of keys we can use for signatures for our commitment_signed message.
713         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
714                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
715
716         let res = {
717                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
718                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
719                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
720                 let local_chan_signer = local_chan.get_signer();
721                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
722                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
723                         INITIAL_COMMITMENT_NUMBER - 1,
724                         push_sats,
725                         channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
726                         opt_anchors, local_funding, remote_funding,
727                         commit_tx_keys.clone(),
728                         non_buffer_feerate + 4,
729                         &mut htlcs,
730                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
731                 );
732                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
733         };
734
735         let commit_signed_msg = msgs::CommitmentSigned {
736                 channel_id: chan.2,
737                 signature: res.0,
738                 htlc_signatures: res.1,
739                 #[cfg(taproot)]
740                 partial_signature_with_nonce: None,
741         };
742
743         let update_fee = msgs::UpdateFee {
744                 channel_id: chan.2,
745                 feerate_per_kw: non_buffer_feerate + 4,
746         };
747
748         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
749
750         //While producing the commitment_signed response after handling a received update_fee request the
751         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
752         //Should produce and error.
753         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
754         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
755         check_added_monitors!(nodes[1], 1);
756         check_closed_broadcast!(nodes[1], true);
757         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
758 }
759
760 #[test]
761 fn test_update_fee_with_fundee_update_add_htlc() {
762         let chanmon_cfgs = create_chanmon_cfgs(2);
763         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
764         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
765         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
766         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
767
768         // balancing
769         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
770
771         {
772                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
773                 *feerate_lock += 20;
774         }
775         nodes[0].node.timer_tick_occurred();
776         check_added_monitors!(nodes[0], 1);
777
778         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
779         assert_eq!(events_0.len(), 1);
780         let (update_msg, commitment_signed) = match events_0[0] {
781                         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 } } => {
782                         (update_fee.as_ref(), commitment_signed)
783                 },
784                 _ => panic!("Unexpected event"),
785         };
786         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
787         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
788         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
789         check_added_monitors!(nodes[1], 1);
790
791         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
792
793         // nothing happens since node[1] is in AwaitingRemoteRevoke
794         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
795         {
796                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
797                 assert_eq!(added_monitors.len(), 0);
798                 added_monitors.clear();
799         }
800         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
801         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
802         // node[1] has nothing to do
803
804         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
805         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
806         check_added_monitors!(nodes[0], 1);
807
808         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
809         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
810         // No commitment_signed so get_event_msg's assert(len == 1) passes
811         check_added_monitors!(nodes[0], 1);
812         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
813         check_added_monitors!(nodes[1], 1);
814         // AwaitingRemoteRevoke ends here
815
816         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
817         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
818         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
819         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
820         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
821         assert_eq!(commitment_update.update_fee.is_none(), true);
822
823         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
824         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
825         check_added_monitors!(nodes[0], 1);
826         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
827
828         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
829         check_added_monitors!(nodes[1], 1);
830         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
831
832         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
833         check_added_monitors!(nodes[1], 1);
834         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
835         // No commitment_signed so get_event_msg's assert(len == 1) passes
836
837         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
838         check_added_monitors!(nodes[0], 1);
839         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
840
841         expect_pending_htlcs_forwardable!(nodes[0]);
842
843         let events = nodes[0].node.get_and_clear_pending_events();
844         assert_eq!(events.len(), 1);
845         match events[0] {
846                 Event::PaymentClaimable { .. } => { },
847                 _ => panic!("Unexpected event"),
848         };
849
850         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
851
852         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
853         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
854         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
855         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
856         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
857 }
858
859 #[test]
860 fn test_update_fee() {
861         let chanmon_cfgs = create_chanmon_cfgs(2);
862         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
863         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
864         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
865         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
866         let channel_id = chan.2;
867
868         // A                                        B
869         // (1) update_fee/commitment_signed      ->
870         //                                       <- (2) revoke_and_ack
871         //                                       .- send (3) commitment_signed
872         // (4) update_fee/commitment_signed      ->
873         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
874         //                                       <- (3) commitment_signed delivered
875         // send (6) revoke_and_ack               -.
876         //                                       <- (5) deliver revoke_and_ack
877         // (6) deliver revoke_and_ack            ->
878         //                                       .- send (7) commitment_signed in response to (4)
879         //                                       <- (7) deliver commitment_signed
880         // revoke_and_ack                        ->
881
882         // Create and deliver (1)...
883         let feerate;
884         {
885                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
886                 feerate = *feerate_lock;
887                 *feerate_lock = feerate + 20;
888         }
889         nodes[0].node.timer_tick_occurred();
890         check_added_monitors!(nodes[0], 1);
891
892         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
893         assert_eq!(events_0.len(), 1);
894         let (update_msg, commitment_signed) = match events_0[0] {
895                         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 } } => {
896                         (update_fee.as_ref(), commitment_signed)
897                 },
898                 _ => panic!("Unexpected event"),
899         };
900         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
901
902         // Generate (2) and (3):
903         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
904         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
905         check_added_monitors!(nodes[1], 1);
906
907         // Deliver (2):
908         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
909         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
910         check_added_monitors!(nodes[0], 1);
911
912         // Create and deliver (4)...
913         {
914                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
915                 *feerate_lock = feerate + 30;
916         }
917         nodes[0].node.timer_tick_occurred();
918         check_added_monitors!(nodes[0], 1);
919         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
920         assert_eq!(events_0.len(), 1);
921         let (update_msg, commitment_signed) = match events_0[0] {
922                         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 } } => {
923                         (update_fee.as_ref(), commitment_signed)
924                 },
925                 _ => panic!("Unexpected event"),
926         };
927
928         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
929         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
930         check_added_monitors!(nodes[1], 1);
931         // ... creating (5)
932         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
933         // No commitment_signed so get_event_msg's assert(len == 1) passes
934
935         // Handle (3), creating (6):
936         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
937         check_added_monitors!(nodes[0], 1);
938         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
939         // No commitment_signed so get_event_msg's assert(len == 1) passes
940
941         // Deliver (5):
942         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
943         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
944         check_added_monitors!(nodes[0], 1);
945
946         // Deliver (6), creating (7):
947         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
948         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
949         assert!(commitment_update.update_add_htlcs.is_empty());
950         assert!(commitment_update.update_fulfill_htlcs.is_empty());
951         assert!(commitment_update.update_fail_htlcs.is_empty());
952         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
953         assert!(commitment_update.update_fee.is_none());
954         check_added_monitors!(nodes[1], 1);
955
956         // Deliver (7)
957         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
958         check_added_monitors!(nodes[0], 1);
959         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
960         // No commitment_signed so get_event_msg's assert(len == 1) passes
961
962         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
963         check_added_monitors!(nodes[1], 1);
964         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
965
966         assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
967         assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
968         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
969         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
970         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
971 }
972
973 #[test]
974 fn fake_network_test() {
975         // Simple test which builds a network of ChannelManagers, connects them to each other, and
976         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
977         let chanmon_cfgs = create_chanmon_cfgs(4);
978         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
979         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
980         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
981
982         // Create some initial channels
983         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
984         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
985         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
986
987         // Rebalance the network a bit by relaying one payment through all the channels...
988         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
989         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
990         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
991         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
992
993         // Send some more payments
994         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
995         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
996         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
997
998         // Test failure packets
999         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1000         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1001
1002         // Add a new channel that skips 3
1003         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1004
1005         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1006         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1007         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1008         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1009         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1010         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1011         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1012
1013         // Do some rebalance loop payments, simultaneously
1014         let mut hops = Vec::with_capacity(3);
1015         hops.push(RouteHop {
1016                 pubkey: nodes[2].node.get_our_node_id(),
1017                 node_features: NodeFeatures::empty(),
1018                 short_channel_id: chan_2.0.contents.short_channel_id,
1019                 channel_features: ChannelFeatures::empty(),
1020                 fee_msat: 0,
1021                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1022         });
1023         hops.push(RouteHop {
1024                 pubkey: nodes[3].node.get_our_node_id(),
1025                 node_features: NodeFeatures::empty(),
1026                 short_channel_id: chan_3.0.contents.short_channel_id,
1027                 channel_features: ChannelFeatures::empty(),
1028                 fee_msat: 0,
1029                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1030         });
1031         hops.push(RouteHop {
1032                 pubkey: nodes[1].node.get_our_node_id(),
1033                 node_features: nodes[1].node.node_features(),
1034                 short_channel_id: chan_4.0.contents.short_channel_id,
1035                 channel_features: nodes[1].node.channel_features(),
1036                 fee_msat: 1000000,
1037                 cltv_expiry_delta: TEST_FINAL_CLTV,
1038         });
1039         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;
1040         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;
1041         let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops], payment_params: None }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1042
1043         let mut hops = Vec::with_capacity(3);
1044         hops.push(RouteHop {
1045                 pubkey: nodes[3].node.get_our_node_id(),
1046                 node_features: NodeFeatures::empty(),
1047                 short_channel_id: chan_4.0.contents.short_channel_id,
1048                 channel_features: ChannelFeatures::empty(),
1049                 fee_msat: 0,
1050                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1051         });
1052         hops.push(RouteHop {
1053                 pubkey: nodes[2].node.get_our_node_id(),
1054                 node_features: NodeFeatures::empty(),
1055                 short_channel_id: chan_3.0.contents.short_channel_id,
1056                 channel_features: ChannelFeatures::empty(),
1057                 fee_msat: 0,
1058                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1059         });
1060         hops.push(RouteHop {
1061                 pubkey: nodes[1].node.get_our_node_id(),
1062                 node_features: nodes[1].node.node_features(),
1063                 short_channel_id: chan_2.0.contents.short_channel_id,
1064                 channel_features: nodes[1].node.channel_features(),
1065                 fee_msat: 1000000,
1066                 cltv_expiry_delta: TEST_FINAL_CLTV,
1067         });
1068         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;
1069         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;
1070         let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops], payment_params: None }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1071
1072         // Claim the rebalances...
1073         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1074         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1075
1076         // Close down the channels...
1077         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1078         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1079         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1080         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1081         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1082         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1083         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1084         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1085         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1086         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1087         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1088         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1089 }
1090
1091 #[test]
1092 fn holding_cell_htlc_counting() {
1093         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1094         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1095         // commitment dance rounds.
1096         let chanmon_cfgs = create_chanmon_cfgs(3);
1097         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1098         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1099         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1100         create_announced_chan_between_nodes(&nodes, 0, 1);
1101         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1102
1103         let mut payments = Vec::new();
1104         for _ in 0..crate::ln::channel::OUR_MAX_HTLCS {
1105                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1106                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
1107                 payments.push((payment_preimage, payment_hash));
1108         }
1109         check_added_monitors!(nodes[1], 1);
1110
1111         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1112         assert_eq!(events.len(), 1);
1113         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1114         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1115
1116         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1117         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1118         // another HTLC.
1119         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1120         {
1121                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)), true, APIError::ChannelUnavailable { ref err },
1122                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1123                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1124                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
1125         }
1126
1127         // This should also be true if we try to forward a payment.
1128         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1129         {
1130                 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1131                 check_added_monitors!(nodes[0], 1);
1132         }
1133
1134         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1135         assert_eq!(events.len(), 1);
1136         let payment_event = SendEvent::from_event(events.pop().unwrap());
1137         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1138
1139         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1140         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1141         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1142         // fails), the second will process the resulting failure and fail the HTLC backward.
1143         expect_pending_htlcs_forwardable!(nodes[1]);
1144         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 }]);
1145         check_added_monitors!(nodes[1], 1);
1146
1147         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1148         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1149         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1150
1151         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1152
1153         // Now forward all the pending HTLCs and claim them back
1154         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1155         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1156         check_added_monitors!(nodes[2], 1);
1157
1158         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1159         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1160         check_added_monitors!(nodes[1], 1);
1161         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1162
1163         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1164         check_added_monitors!(nodes[1], 1);
1165         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1166
1167         for ref update in as_updates.update_add_htlcs.iter() {
1168                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1169         }
1170         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1171         check_added_monitors!(nodes[2], 1);
1172         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1173         check_added_monitors!(nodes[2], 1);
1174         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1175
1176         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1177         check_added_monitors!(nodes[1], 1);
1178         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1179         check_added_monitors!(nodes[1], 1);
1180         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1181
1182         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1183         check_added_monitors!(nodes[2], 1);
1184
1185         expect_pending_htlcs_forwardable!(nodes[2]);
1186
1187         let events = nodes[2].node.get_and_clear_pending_events();
1188         assert_eq!(events.len(), payments.len());
1189         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1190                 match event {
1191                         &Event::PaymentClaimable { ref payment_hash, .. } => {
1192                                 assert_eq!(*payment_hash, *hash);
1193                         },
1194                         _ => panic!("Unexpected event"),
1195                 };
1196         }
1197
1198         for (preimage, _) in payments.drain(..) {
1199                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1200         }
1201
1202         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1203 }
1204
1205 #[test]
1206 fn duplicate_htlc_test() {
1207         // Test that we accept duplicate payment_hash HTLCs across the network and that
1208         // claiming/failing them are all separate and don't affect each other
1209         let chanmon_cfgs = create_chanmon_cfgs(6);
1210         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1211         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1212         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1213
1214         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1215         create_announced_chan_between_nodes(&nodes, 0, 3);
1216         create_announced_chan_between_nodes(&nodes, 1, 3);
1217         create_announced_chan_between_nodes(&nodes, 2, 3);
1218         create_announced_chan_between_nodes(&nodes, 3, 4);
1219         create_announced_chan_between_nodes(&nodes, 3, 5);
1220
1221         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1222
1223         *nodes[0].network_payment_count.borrow_mut() -= 1;
1224         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1225
1226         *nodes[0].network_payment_count.borrow_mut() -= 1;
1227         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1228
1229         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1230         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1231         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1232 }
1233
1234 #[test]
1235 fn test_duplicate_htlc_different_direction_onchain() {
1236         // Test that ChannelMonitor doesn't generate 2 preimage txn
1237         // when we have 2 HTLCs with same preimage that go across a node
1238         // in opposite directions, even with the same payment secret.
1239         let chanmon_cfgs = create_chanmon_cfgs(2);
1240         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1241         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1242         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1243
1244         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1245
1246         // balancing
1247         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1248
1249         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1250
1251         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1252         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1253         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1254
1255         // Provide preimage to node 0 by claiming payment
1256         nodes[0].node.claim_funds(payment_preimage);
1257         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1258         check_added_monitors!(nodes[0], 1);
1259
1260         // Broadcast node 1 commitment txn
1261         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1262
1263         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1264         let mut has_both_htlcs = 0; // check htlcs match ones committed
1265         for outp in remote_txn[0].output.iter() {
1266                 if outp.value == 800_000 / 1000 {
1267                         has_both_htlcs += 1;
1268                 } else if outp.value == 900_000 / 1000 {
1269                         has_both_htlcs += 1;
1270                 }
1271         }
1272         assert_eq!(has_both_htlcs, 2);
1273
1274         mine_transaction(&nodes[0], &remote_txn[0]);
1275         check_added_monitors!(nodes[0], 1);
1276         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1277         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1278
1279         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1280         assert_eq!(claim_txn.len(), 3);
1281
1282         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1283         check_spends!(claim_txn[1], remote_txn[0]);
1284         check_spends!(claim_txn[2], remote_txn[0]);
1285         let preimage_tx = &claim_txn[0];
1286         let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1287                 (&claim_txn[1], &claim_txn[2])
1288         } else {
1289                 (&claim_txn[2], &claim_txn[1])
1290         };
1291
1292         assert_eq!(preimage_tx.input.len(), 1);
1293         assert_eq!(preimage_bump_tx.input.len(), 1);
1294
1295         assert_eq!(preimage_tx.input.len(), 1);
1296         assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1297         assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1298
1299         assert_eq!(timeout_tx.input.len(), 1);
1300         assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1301         check_spends!(timeout_tx, remote_txn[0]);
1302         assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1303
1304         let events = nodes[0].node.get_and_clear_pending_msg_events();
1305         assert_eq!(events.len(), 3);
1306         for e in events {
1307                 match e {
1308                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1309                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1310                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1311                                 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1312                         },
1313                         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, .. } } => {
1314                                 assert!(update_add_htlcs.is_empty());
1315                                 assert!(update_fail_htlcs.is_empty());
1316                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1317                                 assert!(update_fail_malformed_htlcs.is_empty());
1318                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1319                         },
1320                         _ => panic!("Unexpected event"),
1321                 }
1322         }
1323 }
1324
1325 #[test]
1326 fn test_basic_channel_reserve() {
1327         let chanmon_cfgs = create_chanmon_cfgs(2);
1328         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1329         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1330         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1331         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1332
1333         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1334         let channel_reserve = chan_stat.channel_reserve_msat;
1335
1336         // The 2* and +1 are for the fee spike reserve.
1337         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));
1338         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1339         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1340         let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1341         match err {
1342                 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1343                         match &fails[0] {
1344                                 &APIError::ChannelUnavailable{ref err} =>
1345                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1346                                 _ => panic!("Unexpected error variant"),
1347                         }
1348                 },
1349                 _ => panic!("Unexpected error variant"),
1350         }
1351         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1352         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put our balance under counterparty-announced channel reserve value", 1);
1353
1354         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1355 }
1356
1357 #[test]
1358 fn test_fee_spike_violation_fails_htlc() {
1359         let chanmon_cfgs = create_chanmon_cfgs(2);
1360         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1361         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1362         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1363         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1364
1365         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1366         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1367         let secp_ctx = Secp256k1::new();
1368         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1369
1370         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1371
1372         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1373         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1374         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1375         let msg = msgs::UpdateAddHTLC {
1376                 channel_id: chan.2,
1377                 htlc_id: 0,
1378                 amount_msat: htlc_msat,
1379                 payment_hash: payment_hash,
1380                 cltv_expiry: htlc_cltv,
1381                 onion_routing_packet: onion_packet,
1382         };
1383
1384         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1385
1386         // Now manually create the commitment_signed message corresponding to the update_add
1387         // nodes[0] just sent. In the code for construction of this message, "local" refers
1388         // to the sender of the message, and "remote" refers to the receiver.
1389
1390         let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1391
1392         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1393
1394         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1395         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1396         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1397                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1398                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1399                 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1400                 let chan_signer = local_chan.get_signer();
1401                 // Make the signer believe we validated another commitment, so we can release the secret
1402                 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1403
1404                 let pubkeys = chan_signer.pubkeys();
1405                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1406                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1407                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1408                  chan_signer.pubkeys().funding_pubkey)
1409         };
1410         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1411                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1412                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1413                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1414                 let chan_signer = remote_chan.get_signer();
1415                 let pubkeys = chan_signer.pubkeys();
1416                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1417                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1418                  chan_signer.pubkeys().funding_pubkey)
1419         };
1420
1421         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1422         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1423                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1424
1425         // Build the remote commitment transaction so we can sign it, and then later use the
1426         // signature for the commitment_signed message.
1427         let local_chan_balance = 1313;
1428
1429         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1430                 offered: false,
1431                 amount_msat: 3460001,
1432                 cltv_expiry: htlc_cltv,
1433                 payment_hash,
1434                 transaction_output_index: Some(1),
1435         };
1436
1437         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1438
1439         let res = {
1440                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1441                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1442                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
1443                 let local_chan_signer = local_chan.get_signer();
1444                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1445                         commitment_number,
1446                         95000,
1447                         local_chan_balance,
1448                         local_chan.opt_anchors(), local_funding, remote_funding,
1449                         commit_tx_keys.clone(),
1450                         feerate_per_kw,
1451                         &mut vec![(accepted_htlc_info, ())],
1452                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1453                 );
1454                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1455         };
1456
1457         let commit_signed_msg = msgs::CommitmentSigned {
1458                 channel_id: chan.2,
1459                 signature: res.0,
1460                 htlc_signatures: res.1,
1461                 #[cfg(taproot)]
1462                 partial_signature_with_nonce: None,
1463         };
1464
1465         // Send the commitment_signed message to the nodes[1].
1466         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1467         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1468
1469         // Send the RAA to nodes[1].
1470         let raa_msg = msgs::RevokeAndACK {
1471                 channel_id: chan.2,
1472                 per_commitment_secret: local_secret,
1473                 next_per_commitment_point: next_local_point
1474         };
1475         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1476
1477         let events = nodes[1].node.get_and_clear_pending_msg_events();
1478         assert_eq!(events.len(), 1);
1479         // Make sure the HTLC failed in the way we expect.
1480         match events[0] {
1481                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1482                         assert_eq!(update_fail_htlcs.len(), 1);
1483                         update_fail_htlcs[0].clone()
1484                 },
1485                 _ => panic!("Unexpected event"),
1486         };
1487         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1488                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1489
1490         check_added_monitors!(nodes[1], 2);
1491 }
1492
1493 #[test]
1494 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1495         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1496         // Set the fee rate for the channel very high, to the point where the fundee
1497         // sending any above-dust amount would result in a channel reserve violation.
1498         // In this test we check that we would be prevented from sending an HTLC in
1499         // this situation.
1500         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1501         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1502         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1503         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1504         let default_config = UserConfig::default();
1505         let opt_anchors = false;
1506
1507         let mut push_amt = 100_000_000;
1508         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1509
1510         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1511
1512         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1513
1514         // Sending exactly enough to hit the reserve amount should be accepted
1515         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1516                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1517         }
1518
1519         // However one more HTLC should be significantly over the reserve amount and fail.
1520         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1521         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
1522                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1523         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1524         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);
1525 }
1526
1527 #[test]
1528 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1529         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1530         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1531         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1532         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1533         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1534         let default_config = UserConfig::default();
1535         let opt_anchors = false;
1536
1537         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1538         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1539         // transaction fee with 0 HTLCs (183 sats)).
1540         let mut push_amt = 100_000_000;
1541         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1542         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1543         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1544
1545         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1546         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1547                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1548         }
1549
1550         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1551         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1552         let secp_ctx = Secp256k1::new();
1553         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1554         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1555         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1556         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1557         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1558         let msg = msgs::UpdateAddHTLC {
1559                 channel_id: chan.2,
1560                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1561                 amount_msat: htlc_msat,
1562                 payment_hash: payment_hash,
1563                 cltv_expiry: htlc_cltv,
1564                 onion_routing_packet: onion_packet,
1565         };
1566
1567         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1568         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1569         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);
1570         assert_eq!(nodes[0].node.list_channels().len(), 0);
1571         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1572         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1573         check_added_monitors!(nodes[0], 1);
1574         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() });
1575 }
1576
1577 #[test]
1578 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1579         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1580         // calculating our commitment transaction fee (this was previously broken).
1581         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1582         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1583
1584         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1585         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1586         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1587         let default_config = UserConfig::default();
1588         let opt_anchors = false;
1589
1590         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1591         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1592         // transaction fee with 0 HTLCs (183 sats)).
1593         let mut push_amt = 100_000_000;
1594         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1595         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1596         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1597
1598         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1599                 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1600         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1601         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1602         // commitment transaction fee.
1603         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1604
1605         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1606         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1607                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1608         }
1609
1610         // One more than the dust amt should fail, however.
1611         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1612         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
1613                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1614 }
1615
1616 #[test]
1617 fn test_chan_init_feerate_unaffordability() {
1618         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1619         // channel reserve and feerate requirements.
1620         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1621         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1622         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1623         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1624         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1625         let default_config = UserConfig::default();
1626         let opt_anchors = false;
1627
1628         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1629         // HTLC.
1630         let mut push_amt = 100_000_000;
1631         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1632         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1633                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1634
1635         // During open, we don't have a "counterparty channel reserve" to check against, so that
1636         // requirement only comes into play on the open_channel handling side.
1637         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1638         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1639         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1640         open_channel_msg.push_msat += 1;
1641         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1642
1643         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1644         assert_eq!(msg_events.len(), 1);
1645         match msg_events[0] {
1646                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1647                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1648                 },
1649                 _ => panic!("Unexpected event"),
1650         }
1651 }
1652
1653 #[test]
1654 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1655         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1656         // calculating our counterparty's commitment transaction fee (this was previously broken).
1657         let chanmon_cfgs = create_chanmon_cfgs(2);
1658         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1659         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1660         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1661         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1662
1663         let payment_amt = 46000; // Dust amount
1664         // In the previous code, these first four payments would succeed.
1665         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1666         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1667         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1668         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1669
1670         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1671         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1672         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1673         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1674         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1675         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1676
1677         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1678         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1679         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1680         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1681 }
1682
1683 #[test]
1684 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1685         let chanmon_cfgs = create_chanmon_cfgs(3);
1686         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1687         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1688         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1689         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1690         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1691
1692         let feemsat = 239;
1693         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1694         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1695         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1696         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
1697
1698         // Add a 2* and +1 for the fee spike reserve.
1699         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1700         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;
1701         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1702
1703         // Add a pending HTLC.
1704         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1705         let payment_event_1 = {
1706                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1707                 check_added_monitors!(nodes[0], 1);
1708
1709                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1710                 assert_eq!(events.len(), 1);
1711                 SendEvent::from_event(events.remove(0))
1712         };
1713         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1714
1715         // Attempt to trigger a channel reserve violation --> payment failure.
1716         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1717         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;
1718         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1719         let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1720
1721         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1722         let secp_ctx = Secp256k1::new();
1723         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1724         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1725         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1726         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1727         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1728         let msg = msgs::UpdateAddHTLC {
1729                 channel_id: chan.2,
1730                 htlc_id: 1,
1731                 amount_msat: htlc_msat + 1,
1732                 payment_hash: our_payment_hash_1,
1733                 cltv_expiry: htlc_cltv,
1734                 onion_routing_packet: onion_packet,
1735         };
1736
1737         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1738         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1739         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1740         assert_eq!(nodes[1].node.list_channels().len(), 1);
1741         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1742         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1743         check_added_monitors!(nodes[1], 1);
1744         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1745 }
1746
1747 #[test]
1748 fn test_inbound_outbound_capacity_is_not_zero() {
1749         let chanmon_cfgs = create_chanmon_cfgs(2);
1750         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1751         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1752         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1753         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1754         let channels0 = node_chanmgrs[0].list_channels();
1755         let channels1 = node_chanmgrs[1].list_channels();
1756         let default_config = UserConfig::default();
1757         assert_eq!(channels0.len(), 1);
1758         assert_eq!(channels1.len(), 1);
1759
1760         let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1761         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1762         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1763
1764         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1765         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1766 }
1767
1768 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1769         (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1770 }
1771
1772 #[test]
1773 fn test_channel_reserve_holding_cell_htlcs() {
1774         let chanmon_cfgs = create_chanmon_cfgs(3);
1775         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1776         // When this test was written, the default base fee floated based on the HTLC count.
1777         // It is now fixed, so we simply set the fee to the expected value here.
1778         let mut config = test_default_channel_config();
1779         config.channel_config.forwarding_fee_base_msat = 239;
1780         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1781         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1782         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1783         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1784
1785         let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1786         let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1787
1788         let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1789         let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1790
1791         macro_rules! expect_forward {
1792                 ($node: expr) => {{
1793                         let mut events = $node.node.get_and_clear_pending_msg_events();
1794                         assert_eq!(events.len(), 1);
1795                         check_added_monitors!($node, 1);
1796                         let payment_event = SendEvent::from_event(events.remove(0));
1797                         payment_event
1798                 }}
1799         }
1800
1801         let feemsat = 239; // set above
1802         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1803         let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1804         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_1.2);
1805
1806         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1807
1808         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1809         {
1810                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1811                         .with_features(nodes[2].node.invoice_features()).with_max_channel_saturation_power_of_half(0);
1812                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0, TEST_FINAL_CLTV);
1813                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1814                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1815
1816                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
1817                         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)));
1818                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1819                 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);
1820         }
1821
1822         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1823         // nodes[0]'s wealth
1824         loop {
1825                 let amt_msat = recv_value_0 + total_fee_msat;
1826                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1827                 // Also, ensure that each payment has enough to be over the dust limit to
1828                 // ensure it'll be included in each commit tx fee calculation.
1829                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1830                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1831                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1832                         break;
1833                 }
1834
1835                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1836                         .with_features(nodes[2].node.invoice_features()).with_max_channel_saturation_power_of_half(0);
1837                 let route = get_route!(nodes[0], payment_params, recv_value_0, TEST_FINAL_CLTV).unwrap();
1838                 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1839                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1840
1841                 let (stat01_, stat11_, stat12_, stat22_) = (
1842                         get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1843                         get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1844                         get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1845                         get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1846                 );
1847
1848                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1849                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1850                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1851                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1852                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1853         }
1854
1855         // adding pending output.
1856         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1857         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1858         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1859         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1860         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1861         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1862         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1863         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1864         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1865         // policy.
1866         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1867         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1868         let amt_msat_1 = recv_value_1 + total_fee_msat;
1869
1870         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);
1871         let payment_event_1 = {
1872                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1873                 check_added_monitors!(nodes[0], 1);
1874
1875                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1876                 assert_eq!(events.len(), 1);
1877                 SendEvent::from_event(events.remove(0))
1878         };
1879         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1880
1881         // channel reserve test with htlc pending output > 0
1882         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1883         {
1884                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1885                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
1886                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1887                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1888         }
1889
1890         // split the rest to test holding cell
1891         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1892         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1893         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1894         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1895         {
1896                 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1897                 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);
1898         }
1899
1900         // now see if they go through on both sides
1901         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);
1902         // but this will stuck in the holding cell
1903         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1904         check_added_monitors!(nodes[0], 0);
1905         let events = nodes[0].node.get_and_clear_pending_events();
1906         assert_eq!(events.len(), 0);
1907
1908         // test with outbound holding cell amount > 0
1909         {
1910                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1911                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
1912                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1913                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1914                 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put our balance under counterparty-announced channel reserve value", 2);
1915         }
1916
1917         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);
1918         // this will also stuck in the holding cell
1919         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1920         check_added_monitors!(nodes[0], 0);
1921         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1922         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1923
1924         // flush the pending htlc
1925         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1926         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1927         check_added_monitors!(nodes[1], 1);
1928
1929         // the pending htlc should be promoted to committed
1930         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1931         check_added_monitors!(nodes[0], 1);
1932         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1933
1934         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1935         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1936         // No commitment_signed so get_event_msg's assert(len == 1) passes
1937         check_added_monitors!(nodes[0], 1);
1938
1939         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1940         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1941         check_added_monitors!(nodes[1], 1);
1942
1943         expect_pending_htlcs_forwardable!(nodes[1]);
1944
1945         let ref payment_event_11 = expect_forward!(nodes[1]);
1946         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1947         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1948
1949         expect_pending_htlcs_forwardable!(nodes[2]);
1950         expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1951
1952         // flush the htlcs in the holding cell
1953         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1954         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1955         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1956         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1957         expect_pending_htlcs_forwardable!(nodes[1]);
1958
1959         let ref payment_event_3 = expect_forward!(nodes[1]);
1960         assert_eq!(payment_event_3.msgs.len(), 2);
1961         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1962         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1963
1964         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1965         expect_pending_htlcs_forwardable!(nodes[2]);
1966
1967         let events = nodes[2].node.get_and_clear_pending_events();
1968         assert_eq!(events.len(), 2);
1969         match events[0] {
1970                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
1971                         assert_eq!(our_payment_hash_21, *payment_hash);
1972                         assert_eq!(recv_value_21, amount_msat);
1973                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
1974                         assert_eq!(via_channel_id, Some(chan_2.2));
1975                         match &purpose {
1976                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1977                                         assert!(payment_preimage.is_none());
1978                                         assert_eq!(our_payment_secret_21, *payment_secret);
1979                                 },
1980                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1981                         }
1982                 },
1983                 _ => panic!("Unexpected event"),
1984         }
1985         match events[1] {
1986                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
1987                         assert_eq!(our_payment_hash_22, *payment_hash);
1988                         assert_eq!(recv_value_22, amount_msat);
1989                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
1990                         assert_eq!(via_channel_id, Some(chan_2.2));
1991                         match &purpose {
1992                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1993                                         assert!(payment_preimage.is_none());
1994                                         assert_eq!(our_payment_secret_22, *payment_secret);
1995                                 },
1996                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1997                         }
1998                 },
1999                 _ => panic!("Unexpected event"),
2000         }
2001
2002         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2003         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2004         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2005
2006         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2007         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2008         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2009
2010         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2011         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);
2012         let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2013         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2014         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2015
2016         let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2017         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2018 }
2019
2020 #[test]
2021 fn channel_reserve_in_flight_removes() {
2022         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2023         // can send to its counterparty, but due to update ordering, the other side may not yet have
2024         // considered those HTLCs fully removed.
2025         // This tests that we don't count HTLCs which will not be included in the next remote
2026         // commitment transaction towards the reserve value (as it implies no commitment transaction
2027         // will be generated which violates the remote reserve value).
2028         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2029         // To test this we:
2030         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2031         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2032         //    you only consider the value of the first HTLC, it may not),
2033         //  * start routing a third HTLC from A to B,
2034         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2035         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2036         //  * deliver the first fulfill from B
2037         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2038         //    claim,
2039         //  * deliver A's response CS and RAA.
2040         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2041         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2042         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2043         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2044         let chanmon_cfgs = create_chanmon_cfgs(2);
2045         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2046         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2047         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2048         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2049
2050         let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2051         // Route the first two HTLCs.
2052         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2053         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2054         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2055
2056         // Start routing the third HTLC (this is just used to get everyone in the right state).
2057         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2058         let send_1 = {
2059                 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2060                 check_added_monitors!(nodes[0], 1);
2061                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2062                 assert_eq!(events.len(), 1);
2063                 SendEvent::from_event(events.remove(0))
2064         };
2065
2066         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2067         // initial fulfill/CS.
2068         nodes[1].node.claim_funds(payment_preimage_1);
2069         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2070         check_added_monitors!(nodes[1], 1);
2071         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2072
2073         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2074         // remove the second HTLC when we send the HTLC back from B to A.
2075         nodes[1].node.claim_funds(payment_preimage_2);
2076         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2077         check_added_monitors!(nodes[1], 1);
2078         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2079
2080         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2081         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2082         check_added_monitors!(nodes[0], 1);
2083         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2084         expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2085
2086         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2087         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2088         check_added_monitors!(nodes[1], 1);
2089         // B is already AwaitingRAA, so cant generate a CS here
2090         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2091
2092         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2093         check_added_monitors!(nodes[1], 1);
2094         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2095
2096         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2097         check_added_monitors!(nodes[0], 1);
2098         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2099
2100         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2101         check_added_monitors!(nodes[1], 1);
2102         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2103
2104         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2105         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2106         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2107         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2108         // on-chain as necessary).
2109         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2110         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2111         check_added_monitors!(nodes[0], 1);
2112         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2113         expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2114
2115         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2116         check_added_monitors!(nodes[1], 1);
2117         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2118
2119         expect_pending_htlcs_forwardable!(nodes[1]);
2120         expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2121
2122         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2123         // resolve the second HTLC from A's point of view.
2124         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2125         check_added_monitors!(nodes[0], 1);
2126         expect_payment_path_successful!(nodes[0]);
2127         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2128
2129         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2130         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2131         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2132         let send_2 = {
2133                 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2134                 check_added_monitors!(nodes[1], 1);
2135                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2136                 assert_eq!(events.len(), 1);
2137                 SendEvent::from_event(events.remove(0))
2138         };
2139
2140         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2141         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2142         check_added_monitors!(nodes[0], 1);
2143         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2144
2145         // Now just resolve all the outstanding messages/HTLCs for completeness...
2146
2147         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2148         check_added_monitors!(nodes[1], 1);
2149         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
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
2154         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2155         check_added_monitors!(nodes[0], 1);
2156         expect_payment_path_successful!(nodes[0]);
2157         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2158
2159         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2160         check_added_monitors!(nodes[1], 1);
2161         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2162
2163         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2164         check_added_monitors!(nodes[0], 1);
2165
2166         expect_pending_htlcs_forwardable!(nodes[0]);
2167         expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2168
2169         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2170         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2171 }
2172
2173 #[test]
2174 fn channel_monitor_network_test() {
2175         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2176         // tests that ChannelMonitor is able to recover from various states.
2177         let chanmon_cfgs = create_chanmon_cfgs(5);
2178         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2179         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2180         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2181
2182         // Create some initial channels
2183         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2184         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2185         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2186         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2187
2188         // Make sure all nodes are at the same starting height
2189         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2190         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2191         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2192         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2193         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2194
2195         // Rebalance the network a bit by relaying one payment through all the channels...
2196         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2197         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2198         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2199         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2200
2201         // Simple case with no pending HTLCs:
2202         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2203         check_added_monitors!(nodes[1], 1);
2204         check_closed_broadcast!(nodes[1], true);
2205         {
2206                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2207                 assert_eq!(node_txn.len(), 1);
2208                 mine_transaction(&nodes[0], &node_txn[0]);
2209                 check_added_monitors!(nodes[0], 1);
2210                 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2211         }
2212         check_closed_broadcast!(nodes[0], true);
2213         assert_eq!(nodes[0].node.list_channels().len(), 0);
2214         assert_eq!(nodes[1].node.list_channels().len(), 1);
2215         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2216         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2217
2218         // One pending HTLC is discarded by the force-close:
2219         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2220
2221         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2222         // broadcasted until we reach the timelock time).
2223         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2224         check_closed_broadcast!(nodes[1], true);
2225         check_added_monitors!(nodes[1], 1);
2226         {
2227                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2228                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2229                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2230                 mine_transaction(&nodes[2], &node_txn[0]);
2231                 check_added_monitors!(nodes[2], 1);
2232                 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2233         }
2234         check_closed_broadcast!(nodes[2], true);
2235         assert_eq!(nodes[1].node.list_channels().len(), 0);
2236         assert_eq!(nodes[2].node.list_channels().len(), 1);
2237         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2238         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2239
2240         macro_rules! claim_funds {
2241                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2242                         {
2243                                 $node.node.claim_funds($preimage);
2244                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2245                                 check_added_monitors!($node, 1);
2246
2247                                 let events = $node.node.get_and_clear_pending_msg_events();
2248                                 assert_eq!(events.len(), 1);
2249                                 match events[0] {
2250                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2251                                                 assert!(update_add_htlcs.is_empty());
2252                                                 assert!(update_fail_htlcs.is_empty());
2253                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2254                                         },
2255                                         _ => panic!("Unexpected event"),
2256                                 };
2257                         }
2258                 }
2259         }
2260
2261         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2262         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2263         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2264         check_added_monitors!(nodes[2], 1);
2265         check_closed_broadcast!(nodes[2], true);
2266         let node2_commitment_txid;
2267         {
2268                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2269                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2270                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2271                 node2_commitment_txid = node_txn[0].txid();
2272
2273                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2274                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2275                 mine_transaction(&nodes[3], &node_txn[0]);
2276                 check_added_monitors!(nodes[3], 1);
2277                 check_preimage_claim(&nodes[3], &node_txn);
2278         }
2279         check_closed_broadcast!(nodes[3], true);
2280         assert_eq!(nodes[2].node.list_channels().len(), 0);
2281         assert_eq!(nodes[3].node.list_channels().len(), 1);
2282         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2283         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2284
2285         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2286         // confusing us in the following tests.
2287         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2288
2289         // One pending HTLC to time out:
2290         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2291         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2292         // buffer space).
2293
2294         let (close_chan_update_1, close_chan_update_2) = {
2295                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2296                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2297                 assert_eq!(events.len(), 2);
2298                 let close_chan_update_1 = match events[0] {
2299                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2300                                 msg.clone()
2301                         },
2302                         _ => panic!("Unexpected event"),
2303                 };
2304                 match events[1] {
2305                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2306                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2307                         },
2308                         _ => panic!("Unexpected event"),
2309                 }
2310                 check_added_monitors!(nodes[3], 1);
2311
2312                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2313                 {
2314                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2315                         node_txn.retain(|tx| {
2316                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2317                                         false
2318                                 } else { true }
2319                         });
2320                 }
2321
2322                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2323
2324                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2325                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2326
2327                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2328                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2329                 assert_eq!(events.len(), 2);
2330                 let close_chan_update_2 = match events[0] {
2331                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2332                                 msg.clone()
2333                         },
2334                         _ => panic!("Unexpected event"),
2335                 };
2336                 match events[1] {
2337                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2338                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2339                         },
2340                         _ => panic!("Unexpected event"),
2341                 }
2342                 check_added_monitors!(nodes[4], 1);
2343                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2344
2345                 mine_transaction(&nodes[4], &node_txn[0]);
2346                 check_preimage_claim(&nodes[4], &node_txn);
2347                 (close_chan_update_1, close_chan_update_2)
2348         };
2349         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2350         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2351         assert_eq!(nodes[3].node.list_channels().len(), 0);
2352         assert_eq!(nodes[4].node.list_channels().len(), 0);
2353
2354         assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2355                 ChannelMonitorUpdateStatus::Completed);
2356         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2357         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2358 }
2359
2360 #[test]
2361 fn test_justice_tx() {
2362         // Test justice txn built on revoked HTLC-Success tx, against both sides
2363         let mut alice_config = UserConfig::default();
2364         alice_config.channel_handshake_config.announced_channel = true;
2365         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2366         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2367         let mut bob_config = UserConfig::default();
2368         bob_config.channel_handshake_config.announced_channel = true;
2369         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2370         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2371         let user_cfgs = [Some(alice_config), Some(bob_config)];
2372         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2373         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2374         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2375         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2376         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2377         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2378         *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2379         // Create some new channels:
2380         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2381
2382         // A pending HTLC which will be revoked:
2383         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2384         // Get the will-be-revoked local txn from nodes[0]
2385         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2386         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2387         assert_eq!(revoked_local_txn[0].input.len(), 1);
2388         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2389         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2390         assert_eq!(revoked_local_txn[1].input.len(), 1);
2391         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2392         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2393         // Revoke the old state
2394         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2395
2396         {
2397                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2398                 {
2399                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2400                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2401                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2402
2403                         check_spends!(node_txn[0], revoked_local_txn[0]);
2404                         node_txn.swap_remove(0);
2405                 }
2406                 check_added_monitors!(nodes[1], 1);
2407                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2408                 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2409
2410                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2411                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2412                 // Verify broadcast of revoked HTLC-timeout
2413                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2414                 check_added_monitors!(nodes[0], 1);
2415                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2416                 // Broadcast revoked HTLC-timeout on node 1
2417                 mine_transaction(&nodes[1], &node_txn[1]);
2418                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2419         }
2420         get_announce_close_broadcast_events(&nodes, 0, 1);
2421
2422         assert_eq!(nodes[0].node.list_channels().len(), 0);
2423         assert_eq!(nodes[1].node.list_channels().len(), 0);
2424
2425         // We test justice_tx build by A on B's revoked HTLC-Success tx
2426         // Create some new channels:
2427         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2428         {
2429                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2430                 node_txn.clear();
2431         }
2432
2433         // A pending HTLC which will be revoked:
2434         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2435         // Get the will-be-revoked local txn from B
2436         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2437         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2438         assert_eq!(revoked_local_txn[0].input.len(), 1);
2439         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2440         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2441         // Revoke the old state
2442         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2443         {
2444                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2445                 {
2446                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2447                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2448                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2449
2450                         check_spends!(node_txn[0], revoked_local_txn[0]);
2451                         node_txn.swap_remove(0);
2452                 }
2453                 check_added_monitors!(nodes[0], 1);
2454                 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2455
2456                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2457                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2458                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2459                 check_added_monitors!(nodes[1], 1);
2460                 mine_transaction(&nodes[0], &node_txn[1]);
2461                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2462                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2463         }
2464         get_announce_close_broadcast_events(&nodes, 0, 1);
2465         assert_eq!(nodes[0].node.list_channels().len(), 0);
2466         assert_eq!(nodes[1].node.list_channels().len(), 0);
2467 }
2468
2469 #[test]
2470 fn revoked_output_claim() {
2471         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2472         // transaction is broadcast by its counterparty
2473         let chanmon_cfgs = create_chanmon_cfgs(2);
2474         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2475         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2476         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2477         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2478         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2479         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2480         assert_eq!(revoked_local_txn.len(), 1);
2481         // Only output is the full channel value back to nodes[0]:
2482         assert_eq!(revoked_local_txn[0].output.len(), 1);
2483         // Send a payment through, updating everyone's latest commitment txn
2484         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2485
2486         // Inform nodes[1] that nodes[0] broadcast a stale tx
2487         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2488         check_added_monitors!(nodes[1], 1);
2489         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2490         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2491         assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2492
2493         check_spends!(node_txn[0], revoked_local_txn[0]);
2494
2495         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2496         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2497         get_announce_close_broadcast_events(&nodes, 0, 1);
2498         check_added_monitors!(nodes[0], 1);
2499         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2500 }
2501
2502 #[test]
2503 fn claim_htlc_outputs_shared_tx() {
2504         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2505         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2506         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2507         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2508         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2509         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2510
2511         // Create some new channel:
2512         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2513
2514         // Rebalance the network to generate htlc in the two directions
2515         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2516         // 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
2517         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2518         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2519
2520         // Get the will-be-revoked local txn from node[0]
2521         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2522         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2523         assert_eq!(revoked_local_txn[0].input.len(), 1);
2524         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2525         assert_eq!(revoked_local_txn[1].input.len(), 1);
2526         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2527         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2528         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2529
2530         //Revoke the old state
2531         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2532
2533         {
2534                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2535                 check_added_monitors!(nodes[0], 1);
2536                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2537                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2538                 check_added_monitors!(nodes[1], 1);
2539                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2540                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2541                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2542
2543                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2544                 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2545
2546                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2547                 check_spends!(node_txn[0], revoked_local_txn[0]);
2548
2549                 let mut witness_lens = BTreeSet::new();
2550                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2551                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2552                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2553                 assert_eq!(witness_lens.len(), 3);
2554                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2555                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2556                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2557
2558                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2559                 // ANTI_REORG_DELAY confirmations.
2560                 mine_transaction(&nodes[1], &node_txn[0]);
2561                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2562                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2563         }
2564         get_announce_close_broadcast_events(&nodes, 0, 1);
2565         assert_eq!(nodes[0].node.list_channels().len(), 0);
2566         assert_eq!(nodes[1].node.list_channels().len(), 0);
2567 }
2568
2569 #[test]
2570 fn claim_htlc_outputs_single_tx() {
2571         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2572         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2573         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2574         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2575         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2576         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2577
2578         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2579
2580         // Rebalance the network to generate htlc in the two directions
2581         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2582         // 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
2583         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2584         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2585         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2586
2587         // Get the will-be-revoked local txn from node[0]
2588         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2589
2590         //Revoke the old state
2591         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2592
2593         {
2594                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2595                 check_added_monitors!(nodes[0], 1);
2596                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2597                 check_added_monitors!(nodes[1], 1);
2598                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2599                 let mut events = nodes[0].node.get_and_clear_pending_events();
2600                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2601                 match events.last().unwrap() {
2602                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2603                         _ => panic!("Unexpected event"),
2604                 }
2605
2606                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2607                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2608
2609                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2610                 assert_eq!(node_txn.len(), 7);
2611
2612                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2613                 assert_eq!(node_txn[0].input.len(), 1);
2614                 check_spends!(node_txn[0], chan_1.3);
2615                 assert_eq!(node_txn[1].input.len(), 1);
2616                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2617                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2618                 check_spends!(node_txn[1], node_txn[0]);
2619
2620                 // Justice transactions are indices 2-3-4
2621                 assert_eq!(node_txn[2].input.len(), 1);
2622                 assert_eq!(node_txn[3].input.len(), 1);
2623                 assert_eq!(node_txn[4].input.len(), 1);
2624
2625                 check_spends!(node_txn[2], revoked_local_txn[0]);
2626                 check_spends!(node_txn[3], revoked_local_txn[0]);
2627                 check_spends!(node_txn[4], revoked_local_txn[0]);
2628
2629                 let mut witness_lens = BTreeSet::new();
2630                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2631                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2632                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2633                 assert_eq!(witness_lens.len(), 3);
2634                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2635                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2636                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2637
2638                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2639                 // ANTI_REORG_DELAY confirmations.
2640                 mine_transaction(&nodes[1], &node_txn[2]);
2641                 mine_transaction(&nodes[1], &node_txn[3]);
2642                 mine_transaction(&nodes[1], &node_txn[4]);
2643                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2644                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2645         }
2646         get_announce_close_broadcast_events(&nodes, 0, 1);
2647         assert_eq!(nodes[0].node.list_channels().len(), 0);
2648         assert_eq!(nodes[1].node.list_channels().len(), 0);
2649 }
2650
2651 #[test]
2652 fn test_htlc_on_chain_success() {
2653         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2654         // the preimage backward accordingly. So here we test that ChannelManager is
2655         // broadcasting the right event to other nodes in payment path.
2656         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2657         // A --------------------> B ----------------------> C (preimage)
2658         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2659         // commitment transaction was broadcast.
2660         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2661         // towards B.
2662         // B should be able to claim via preimage if A then broadcasts its local tx.
2663         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2664         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2665         // PaymentSent event).
2666
2667         let chanmon_cfgs = create_chanmon_cfgs(3);
2668         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2669         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2670         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2671
2672         // Create some initial channels
2673         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2674         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2675
2676         // Ensure all nodes are at the same height
2677         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2678         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2679         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2680         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2681
2682         // Rebalance the network a bit by relaying one payment through all the channels...
2683         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2684         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2685
2686         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2687         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2688
2689         // Broadcast legit commitment tx from C on B's chain
2690         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2691         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2692         assert_eq!(commitment_tx.len(), 1);
2693         check_spends!(commitment_tx[0], chan_2.3);
2694         nodes[2].node.claim_funds(our_payment_preimage);
2695         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2696         nodes[2].node.claim_funds(our_payment_preimage_2);
2697         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2698         check_added_monitors!(nodes[2], 2);
2699         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2700         assert!(updates.update_add_htlcs.is_empty());
2701         assert!(updates.update_fail_htlcs.is_empty());
2702         assert!(updates.update_fail_malformed_htlcs.is_empty());
2703         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2704
2705         mine_transaction(&nodes[2], &commitment_tx[0]);
2706         check_closed_broadcast!(nodes[2], true);
2707         check_added_monitors!(nodes[2], 1);
2708         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2709         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2710         assert_eq!(node_txn.len(), 2);
2711         check_spends!(node_txn[0], commitment_tx[0]);
2712         check_spends!(node_txn[1], commitment_tx[0]);
2713         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2714         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2715         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2716         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2717         assert_eq!(node_txn[0].lock_time.0, 0);
2718         assert_eq!(node_txn[1].lock_time.0, 0);
2719
2720         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2721         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2722         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone(), node_txn[1].clone()]});
2723         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2724         {
2725                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2726                 assert_eq!(added_monitors.len(), 1);
2727                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2728                 added_monitors.clear();
2729         }
2730         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2731         assert_eq!(forwarded_events.len(), 3);
2732         match forwarded_events[0] {
2733                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2734                 _ => panic!("Unexpected event"),
2735         }
2736         let chan_id = Some(chan_1.2);
2737         match forwarded_events[1] {
2738                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2739                         assert_eq!(fee_earned_msat, Some(1000));
2740                         assert_eq!(prev_channel_id, chan_id);
2741                         assert_eq!(claim_from_onchain_tx, true);
2742                         assert_eq!(next_channel_id, Some(chan_2.2));
2743                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2744                 },
2745                 _ => panic!()
2746         }
2747         match forwarded_events[2] {
2748                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2749                         assert_eq!(fee_earned_msat, Some(1000));
2750                         assert_eq!(prev_channel_id, chan_id);
2751                         assert_eq!(claim_from_onchain_tx, true);
2752                         assert_eq!(next_channel_id, Some(chan_2.2));
2753                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2754                 },
2755                 _ => panic!()
2756         }
2757         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2758         {
2759                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2760                 assert_eq!(added_monitors.len(), 2);
2761                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2762                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2763                 added_monitors.clear();
2764         }
2765         assert_eq!(events.len(), 3);
2766
2767         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2768         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2769
2770         match nodes_2_event {
2771                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2772                 _ => panic!("Unexpected event"),
2773         }
2774
2775         match nodes_0_event {
2776                 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, .. } } => {
2777                         assert!(update_add_htlcs.is_empty());
2778                         assert!(update_fail_htlcs.is_empty());
2779                         assert_eq!(update_fulfill_htlcs.len(), 1);
2780                         assert!(update_fail_malformed_htlcs.is_empty());
2781                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2782                 },
2783                 _ => panic!("Unexpected event"),
2784         };
2785
2786         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2787         match events[0] {
2788                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2789                 _ => panic!("Unexpected event"),
2790         }
2791
2792         macro_rules! check_tx_local_broadcast {
2793                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2794                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2795                         assert_eq!(node_txn.len(), 2);
2796                         // Node[1]: 2 * HTLC-timeout tx
2797                         // Node[0]: 2 * HTLC-timeout tx
2798                         check_spends!(node_txn[0], $commitment_tx);
2799                         check_spends!(node_txn[1], $commitment_tx);
2800                         assert_ne!(node_txn[0].lock_time.0, 0);
2801                         assert_ne!(node_txn[1].lock_time.0, 0);
2802                         if $htlc_offered {
2803                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2804                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2805                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2806                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2807                         } else {
2808                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2809                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2810                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2811                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2812                         }
2813                         node_txn.clear();
2814                 } }
2815         }
2816         // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2817         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2818
2819         // Broadcast legit commitment tx from A on B's chain
2820         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2821         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2822         check_spends!(node_a_commitment_tx[0], chan_1.3);
2823         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2824         check_closed_broadcast!(nodes[1], true);
2825         check_added_monitors!(nodes[1], 1);
2826         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2827         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2828         assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2829         let commitment_spend =
2830                 if node_txn.len() == 1 {
2831                         &node_txn[0]
2832                 } else {
2833                         // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2834                         // FullBlockViaListen
2835                         if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2836                                 check_spends!(node_txn[1], commitment_tx[0]);
2837                                 check_spends!(node_txn[2], commitment_tx[0]);
2838                                 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2839                                 &node_txn[0]
2840                         } else {
2841                                 check_spends!(node_txn[0], commitment_tx[0]);
2842                                 check_spends!(node_txn[1], commitment_tx[0]);
2843                                 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2844                                 &node_txn[2]
2845                         }
2846                 };
2847
2848         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2849         assert_eq!(commitment_spend.input.len(), 2);
2850         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2851         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2852         assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1 + 1);
2853         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2854         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2855         // we already checked the same situation with A.
2856
2857         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2858         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2859         connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2860         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2861         check_closed_broadcast!(nodes[0], true);
2862         check_added_monitors!(nodes[0], 1);
2863         let events = nodes[0].node.get_and_clear_pending_events();
2864         assert_eq!(events.len(), 5);
2865         let mut first_claimed = false;
2866         for event in events {
2867                 match event {
2868                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2869                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2870                                         assert!(!first_claimed);
2871                                         first_claimed = true;
2872                                 } else {
2873                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2874                                         assert_eq!(payment_hash, payment_hash_2);
2875                                 }
2876                         },
2877                         Event::PaymentPathSuccessful { .. } => {},
2878                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2879                         _ => panic!("Unexpected event"),
2880                 }
2881         }
2882         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
2883 }
2884
2885 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2886         // Test that in case of a unilateral close onchain, we detect the state of output and
2887         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2888         // broadcasting the right event to other nodes in payment path.
2889         // A ------------------> B ----------------------> C (timeout)
2890         //    B's commitment tx                 C's commitment tx
2891         //            \                                  \
2892         //         B's HTLC timeout tx               B's timeout tx
2893
2894         let chanmon_cfgs = create_chanmon_cfgs(3);
2895         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2896         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2897         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2898         *nodes[0].connect_style.borrow_mut() = connect_style;
2899         *nodes[1].connect_style.borrow_mut() = connect_style;
2900         *nodes[2].connect_style.borrow_mut() = connect_style;
2901
2902         // Create some intial channels
2903         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2904         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2905
2906         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2907         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2908         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2909
2910         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2911
2912         // Broadcast legit commitment tx from C on B's chain
2913         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2914         check_spends!(commitment_tx[0], chan_2.3);
2915         nodes[2].node.fail_htlc_backwards(&payment_hash);
2916         check_added_monitors!(nodes[2], 0);
2917         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2918         check_added_monitors!(nodes[2], 1);
2919
2920         let events = nodes[2].node.get_and_clear_pending_msg_events();
2921         assert_eq!(events.len(), 1);
2922         match events[0] {
2923                 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, .. } } => {
2924                         assert!(update_add_htlcs.is_empty());
2925                         assert!(!update_fail_htlcs.is_empty());
2926                         assert!(update_fulfill_htlcs.is_empty());
2927                         assert!(update_fail_malformed_htlcs.is_empty());
2928                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2929                 },
2930                 _ => panic!("Unexpected event"),
2931         };
2932         mine_transaction(&nodes[2], &commitment_tx[0]);
2933         check_closed_broadcast!(nodes[2], true);
2934         check_added_monitors!(nodes[2], 1);
2935         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2936         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2937         assert_eq!(node_txn.len(), 0);
2938
2939         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2940         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2941         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2942         mine_transaction(&nodes[1], &commitment_tx[0]);
2943         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2944         let timeout_tx;
2945         {
2946                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2947                 assert_eq!(node_txn.len(), 3); // 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2948
2949                 check_spends!(node_txn[2], commitment_tx[0]);
2950                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2951
2952                 check_spends!(node_txn[0], chan_2.3);
2953                 check_spends!(node_txn[1], node_txn[0]);
2954                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2955                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2956
2957                 timeout_tx = node_txn[2].clone();
2958                 node_txn.clear();
2959         }
2960
2961         mine_transaction(&nodes[1], &timeout_tx);
2962         check_added_monitors!(nodes[1], 1);
2963         check_closed_broadcast!(nodes[1], true);
2964
2965         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2966
2967         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 }]);
2968         check_added_monitors!(nodes[1], 1);
2969         let events = nodes[1].node.get_and_clear_pending_msg_events();
2970         assert_eq!(events.len(), 1);
2971         match events[0] {
2972                 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, .. } } => {
2973                         assert!(update_add_htlcs.is_empty());
2974                         assert!(!update_fail_htlcs.is_empty());
2975                         assert!(update_fulfill_htlcs.is_empty());
2976                         assert!(update_fail_malformed_htlcs.is_empty());
2977                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2978                 },
2979                 _ => panic!("Unexpected event"),
2980         };
2981
2982         // Broadcast legit commitment tx from B on A's chain
2983         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2984         check_spends!(commitment_tx[0], chan_1.3);
2985
2986         mine_transaction(&nodes[0], &commitment_tx[0]);
2987         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2988
2989         check_closed_broadcast!(nodes[0], true);
2990         check_added_monitors!(nodes[0], 1);
2991         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2992         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
2993         assert_eq!(node_txn.len(), 1);
2994         check_spends!(node_txn[0], commitment_tx[0]);
2995         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2996 }
2997
2998 #[test]
2999 fn test_htlc_on_chain_timeout() {
3000         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3001         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3002         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3003 }
3004
3005 #[test]
3006 fn test_simple_commitment_revoked_fail_backward() {
3007         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3008         // and fail backward accordingly.
3009
3010         let chanmon_cfgs = create_chanmon_cfgs(3);
3011         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3012         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3013         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3014
3015         // Create some initial channels
3016         create_announced_chan_between_nodes(&nodes, 0, 1);
3017         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3018
3019         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3020         // Get the will-be-revoked local txn from nodes[2]
3021         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3022         // Revoke the old state
3023         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3024
3025         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3026
3027         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3028         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3029         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3030         check_added_monitors!(nodes[1], 1);
3031         check_closed_broadcast!(nodes[1], true);
3032
3033         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 }]);
3034         check_added_monitors!(nodes[1], 1);
3035         let events = nodes[1].node.get_and_clear_pending_msg_events();
3036         assert_eq!(events.len(), 1);
3037         match events[0] {
3038                 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, .. } } => {
3039                         assert!(update_add_htlcs.is_empty());
3040                         assert_eq!(update_fail_htlcs.len(), 1);
3041                         assert!(update_fulfill_htlcs.is_empty());
3042                         assert!(update_fail_malformed_htlcs.is_empty());
3043                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3044
3045                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3046                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3047                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3048                 },
3049                 _ => panic!("Unexpected event"),
3050         }
3051 }
3052
3053 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3054         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3055         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3056         // commitment transaction anymore.
3057         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3058         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3059         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3060         // technically disallowed and we should probably handle it reasonably.
3061         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3062         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3063         // transactions:
3064         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3065         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3066         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3067         //   and once they revoke the previous commitment transaction (allowing us to send a new
3068         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3069         let chanmon_cfgs = create_chanmon_cfgs(3);
3070         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3071         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3072         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3073
3074         // Create some initial channels
3075         create_announced_chan_between_nodes(&nodes, 0, 1);
3076         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3077
3078         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 });
3079         // Get the will-be-revoked local txn from nodes[2]
3080         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3081         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3082         // Revoke the old state
3083         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3084
3085         let value = if use_dust {
3086                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3087                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3088                 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3089                         .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3090         } else { 3000000 };
3091
3092         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3093         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3094         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3095
3096         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3097         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3098         check_added_monitors!(nodes[2], 1);
3099         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3100         assert!(updates.update_add_htlcs.is_empty());
3101         assert!(updates.update_fulfill_htlcs.is_empty());
3102         assert!(updates.update_fail_malformed_htlcs.is_empty());
3103         assert_eq!(updates.update_fail_htlcs.len(), 1);
3104         assert!(updates.update_fee.is_none());
3105         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3106         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3107         // Drop the last RAA from 3 -> 2
3108
3109         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3110         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3111         check_added_monitors!(nodes[2], 1);
3112         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3113         assert!(updates.update_add_htlcs.is_empty());
3114         assert!(updates.update_fulfill_htlcs.is_empty());
3115         assert!(updates.update_fail_malformed_htlcs.is_empty());
3116         assert_eq!(updates.update_fail_htlcs.len(), 1);
3117         assert!(updates.update_fee.is_none());
3118         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3119         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3120         check_added_monitors!(nodes[1], 1);
3121         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3122         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3123         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3124         check_added_monitors!(nodes[2], 1);
3125
3126         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3127         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3128         check_added_monitors!(nodes[2], 1);
3129         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3130         assert!(updates.update_add_htlcs.is_empty());
3131         assert!(updates.update_fulfill_htlcs.is_empty());
3132         assert!(updates.update_fail_malformed_htlcs.is_empty());
3133         assert_eq!(updates.update_fail_htlcs.len(), 1);
3134         assert!(updates.update_fee.is_none());
3135         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3136         // At this point first_payment_hash has dropped out of the latest two commitment
3137         // transactions that nodes[1] is tracking...
3138         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3139         check_added_monitors!(nodes[1], 1);
3140         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3141         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3142         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3143         check_added_monitors!(nodes[2], 1);
3144
3145         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3146         // on nodes[2]'s RAA.
3147         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3148         nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3149         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3150         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3151         check_added_monitors!(nodes[1], 0);
3152
3153         if deliver_bs_raa {
3154                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3155                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3156                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3157                 check_added_monitors!(nodes[1], 1);
3158                 let events = nodes[1].node.get_and_clear_pending_events();
3159                 assert_eq!(events.len(), 2);
3160                 match events[0] {
3161                         Event::PendingHTLCsForwardable { .. } => { },
3162                         _ => panic!("Unexpected event"),
3163                 };
3164                 match events[1] {
3165                         Event::HTLCHandlingFailed { .. } => { },
3166                         _ => panic!("Unexpected event"),
3167                 }
3168                 // Deliberately don't process the pending fail-back so they all fail back at once after
3169                 // block connection just like the !deliver_bs_raa case
3170         }
3171
3172         let mut failed_htlcs = HashSet::new();
3173         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3174
3175         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3176         check_added_monitors!(nodes[1], 1);
3177         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3178
3179         let events = nodes[1].node.get_and_clear_pending_events();
3180         assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3181         match events[0] {
3182                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3183                 _ => panic!("Unexepected event"),
3184         }
3185         match events[1] {
3186                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3187                         assert_eq!(*payment_hash, fourth_payment_hash);
3188                 },
3189                 _ => panic!("Unexpected event"),
3190         }
3191         match events[2] {
3192                 Event::PaymentFailed { ref payment_hash, .. } => {
3193                         assert_eq!(*payment_hash, fourth_payment_hash);
3194                 },
3195                 _ => panic!("Unexpected event"),
3196         }
3197
3198         nodes[1].node.process_pending_htlc_forwards();
3199         check_added_monitors!(nodes[1], 1);
3200
3201         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3202         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3203
3204         if deliver_bs_raa {
3205                 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3206                 match nodes_2_event {
3207                         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, .. } } => {
3208                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3209                                 assert_eq!(update_add_htlcs.len(), 1);
3210                                 assert!(update_fulfill_htlcs.is_empty());
3211                                 assert!(update_fail_htlcs.is_empty());
3212                                 assert!(update_fail_malformed_htlcs.is_empty());
3213                         },
3214                         _ => panic!("Unexpected event"),
3215                 }
3216         }
3217
3218         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3219         match nodes_2_event {
3220                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3221                         assert_eq!(channel_id, chan_2.2);
3222                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3223                 },
3224                 _ => panic!("Unexpected event"),
3225         }
3226
3227         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3228         match nodes_0_event {
3229                 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, .. } } => {
3230                         assert!(update_add_htlcs.is_empty());
3231                         assert_eq!(update_fail_htlcs.len(), 3);
3232                         assert!(update_fulfill_htlcs.is_empty());
3233                         assert!(update_fail_malformed_htlcs.is_empty());
3234                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3235
3236                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3237                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3238                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3239
3240                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3241
3242                         let events = nodes[0].node.get_and_clear_pending_events();
3243                         assert_eq!(events.len(), 6);
3244                         match events[0] {
3245                                 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3246                                         assert!(failed_htlcs.insert(payment_hash.0));
3247                                         // If we delivered B's RAA we got an unknown preimage error, not something
3248                                         // that we should update our routing table for.
3249                                         if !deliver_bs_raa {
3250                                                 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3251                                         }
3252                                 },
3253                                 _ => panic!("Unexpected event"),
3254                         }
3255                         match events[1] {
3256                                 Event::PaymentFailed { ref payment_hash, .. } => {
3257                                         assert_eq!(*payment_hash, first_payment_hash);
3258                                 },
3259                                 _ => panic!("Unexpected event"),
3260                         }
3261                         match events[2] {
3262                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3263                                         assert!(failed_htlcs.insert(payment_hash.0));
3264                                 },
3265                                 _ => panic!("Unexpected event"),
3266                         }
3267                         match events[3] {
3268                                 Event::PaymentFailed { ref payment_hash, .. } => {
3269                                         assert_eq!(*payment_hash, second_payment_hash);
3270                                 },
3271                                 _ => panic!("Unexpected event"),
3272                         }
3273                         match events[4] {
3274                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3275                                         assert!(failed_htlcs.insert(payment_hash.0));
3276                                 },
3277                                 _ => panic!("Unexpected event"),
3278                         }
3279                         match events[5] {
3280                                 Event::PaymentFailed { ref payment_hash, .. } => {
3281                                         assert_eq!(*payment_hash, third_payment_hash);
3282                                 },
3283                                 _ => panic!("Unexpected event"),
3284                         }
3285                 },
3286                 _ => panic!("Unexpected event"),
3287         }
3288
3289         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3290         match events[0] {
3291                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3292                 _ => panic!("Unexpected event"),
3293         }
3294
3295         assert!(failed_htlcs.contains(&first_payment_hash.0));
3296         assert!(failed_htlcs.contains(&second_payment_hash.0));
3297         assert!(failed_htlcs.contains(&third_payment_hash.0));
3298 }
3299
3300 #[test]
3301 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3302         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3303         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3304         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3305         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3306 }
3307
3308 #[test]
3309 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3310         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3311         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3312         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3313         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3314 }
3315
3316 #[test]
3317 fn fail_backward_pending_htlc_upon_channel_failure() {
3318         let chanmon_cfgs = create_chanmon_cfgs(2);
3319         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3320         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3321         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3322         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3323
3324         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3325         {
3326                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3327                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
3328                 check_added_monitors!(nodes[0], 1);
3329
3330                 let payment_event = {
3331                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3332                         assert_eq!(events.len(), 1);
3333                         SendEvent::from_event(events.remove(0))
3334                 };
3335                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3336                 assert_eq!(payment_event.msgs.len(), 1);
3337         }
3338
3339         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3340         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3341         {
3342                 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3343                 check_added_monitors!(nodes[0], 0);
3344
3345                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3346         }
3347
3348         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3349         {
3350                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3351
3352                 let secp_ctx = Secp256k1::new();
3353                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3354                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3355                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3356                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3357                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3358
3359                 // Send a 0-msat update_add_htlc to fail the channel.
3360                 let update_add_htlc = msgs::UpdateAddHTLC {
3361                         channel_id: chan.2,
3362                         htlc_id: 0,
3363                         amount_msat: 0,
3364                         payment_hash,
3365                         cltv_expiry,
3366                         onion_routing_packet,
3367                 };
3368                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3369         }
3370         let events = nodes[0].node.get_and_clear_pending_events();
3371         assert_eq!(events.len(), 3);
3372         // Check that Alice fails backward the pending HTLC from the second payment.
3373         match events[0] {
3374                 Event::PaymentPathFailed { payment_hash, .. } => {
3375                         assert_eq!(payment_hash, failed_payment_hash);
3376                 },
3377                 _ => panic!("Unexpected event"),
3378         }
3379         match events[1] {
3380                 Event::PaymentFailed { payment_hash, .. } => {
3381                         assert_eq!(payment_hash, failed_payment_hash);
3382                 },
3383                 _ => panic!("Unexpected event"),
3384         }
3385         match events[2] {
3386                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3387                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3388                 },
3389                 _ => panic!("Unexpected event {:?}", events[1]),
3390         }
3391         check_closed_broadcast!(nodes[0], true);
3392         check_added_monitors!(nodes[0], 1);
3393 }
3394
3395 #[test]
3396 fn test_htlc_ignore_latest_remote_commitment() {
3397         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3398         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3399         let chanmon_cfgs = create_chanmon_cfgs(2);
3400         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3401         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3402         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3403         if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3404                 // We rely on the ability to connect a block redundantly, which isn't allowed via
3405                 // `chain::Listen`, so we never run the test if we randomly get assigned that
3406                 // connect_style.
3407                 return;
3408         }
3409         create_announced_chan_between_nodes(&nodes, 0, 1);
3410
3411         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3412         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3413         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3414         check_closed_broadcast!(nodes[0], true);
3415         check_added_monitors!(nodes[0], 1);
3416         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3417
3418         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3419         assert_eq!(node_txn.len(), 3);
3420         assert_eq!(node_txn[0], node_txn[1]);
3421
3422         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
3423         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3424         check_closed_broadcast!(nodes[1], true);
3425         check_added_monitors!(nodes[1], 1);
3426         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3427
3428         // Duplicate the connect_block call since this may happen due to other listeners
3429         // registering new transactions
3430         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3431 }
3432
3433 #[test]
3434 fn test_force_close_fail_back() {
3435         // Check which HTLCs are failed-backwards on channel force-closure
3436         let chanmon_cfgs = create_chanmon_cfgs(3);
3437         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3438         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3439         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3440         create_announced_chan_between_nodes(&nodes, 0, 1);
3441         create_announced_chan_between_nodes(&nodes, 1, 2);
3442
3443         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3444
3445         let mut payment_event = {
3446                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3447                 check_added_monitors!(nodes[0], 1);
3448
3449                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3450                 assert_eq!(events.len(), 1);
3451                 SendEvent::from_event(events.remove(0))
3452         };
3453
3454         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3455         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3456
3457         expect_pending_htlcs_forwardable!(nodes[1]);
3458
3459         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3460         assert_eq!(events_2.len(), 1);
3461         payment_event = SendEvent::from_event(events_2.remove(0));
3462         assert_eq!(payment_event.msgs.len(), 1);
3463
3464         check_added_monitors!(nodes[1], 1);
3465         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3466         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3467         check_added_monitors!(nodes[2], 1);
3468         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3469
3470         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3471         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3472         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3473
3474         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3475         check_closed_broadcast!(nodes[2], true);
3476         check_added_monitors!(nodes[2], 1);
3477         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3478         let tx = {
3479                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3480                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3481                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3482                 // back to nodes[1] upon timeout otherwise.
3483                 assert_eq!(node_txn.len(), 1);
3484                 node_txn.remove(0)
3485         };
3486
3487         mine_transaction(&nodes[1], &tx);
3488
3489         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3490         check_closed_broadcast!(nodes[1], true);
3491         check_added_monitors!(nodes[1], 1);
3492         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3493
3494         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3495         {
3496                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3497                         .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);
3498         }
3499         mine_transaction(&nodes[2], &tx);
3500         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3501         assert_eq!(node_txn.len(), 1);
3502         assert_eq!(node_txn[0].input.len(), 1);
3503         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3504         assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3505         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3506
3507         check_spends!(node_txn[0], tx);
3508 }
3509
3510 #[test]
3511 fn test_dup_events_on_peer_disconnect() {
3512         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3513         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3514         // as we used to generate the event immediately upon receipt of the payment preimage in the
3515         // update_fulfill_htlc message.
3516
3517         let chanmon_cfgs = create_chanmon_cfgs(2);
3518         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3519         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3520         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3521         create_announced_chan_between_nodes(&nodes, 0, 1);
3522
3523         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3524
3525         nodes[1].node.claim_funds(payment_preimage);
3526         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3527         check_added_monitors!(nodes[1], 1);
3528         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3529         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3530         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3531
3532         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3533         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3534
3535         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3536         expect_payment_path_successful!(nodes[0]);
3537 }
3538
3539 #[test]
3540 fn test_peer_disconnected_before_funding_broadcasted() {
3541         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3542         // before the funding transaction has been broadcasted.
3543         let chanmon_cfgs = create_chanmon_cfgs(2);
3544         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3545         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3546         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3547
3548         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3549         // broadcasted, even though it's created by `nodes[0]`.
3550         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();
3551         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3552         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3553         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3554         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3555
3556         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3557         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3558
3559         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3560
3561         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3562         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3563
3564         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3565         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3566         // broadcasted.
3567         {
3568                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3569         }
3570
3571         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3572         // disconnected before the funding transaction was broadcasted.
3573         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3574         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3575
3576         check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3577         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3578 }
3579
3580 #[test]
3581 fn test_simple_peer_disconnect() {
3582         // Test that we can reconnect when there are no lost messages
3583         let chanmon_cfgs = create_chanmon_cfgs(3);
3584         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3585         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3586         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3587         create_announced_chan_between_nodes(&nodes, 0, 1);
3588         create_announced_chan_between_nodes(&nodes, 1, 2);
3589
3590         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3591         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3592         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3593
3594         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3595         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3596         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3597         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3598
3599         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3600         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3601         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3602
3603         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3604         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3605         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3606         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3607
3608         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3609         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3610
3611         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3612         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3613
3614         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3615         {
3616                 let events = nodes[0].node.get_and_clear_pending_events();
3617                 assert_eq!(events.len(), 4);
3618                 match events[0] {
3619                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3620                                 assert_eq!(payment_preimage, payment_preimage_3);
3621                                 assert_eq!(payment_hash, payment_hash_3);
3622                         },
3623                         _ => panic!("Unexpected event"),
3624                 }
3625                 match events[1] {
3626                         Event::PaymentPathSuccessful { .. } => {},
3627                         _ => panic!("Unexpected event"),
3628                 }
3629                 match events[2] {
3630                         Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3631                                 assert_eq!(payment_hash, payment_hash_5);
3632                                 assert!(payment_failed_permanently);
3633                         },
3634                         _ => panic!("Unexpected event"),
3635                 }
3636                 match events[3] {
3637                         Event::PaymentFailed { payment_hash, .. } => {
3638                                 assert_eq!(payment_hash, payment_hash_5);
3639                         },
3640                         _ => panic!("Unexpected event"),
3641                 }
3642         }
3643
3644         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3645         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3646 }
3647
3648 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3649         // Test that we can reconnect when in-flight HTLC updates get dropped
3650         let chanmon_cfgs = create_chanmon_cfgs(2);
3651         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3652         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3653         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3654
3655         let mut as_channel_ready = None;
3656         let channel_id = if messages_delivered == 0 {
3657                 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3658                 as_channel_ready = Some(channel_ready);
3659                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3660                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3661                 // it before the channel_reestablish message.
3662                 chan_id
3663         } else {
3664                 create_announced_chan_between_nodes(&nodes, 0, 1).2
3665         };
3666
3667         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3668
3669         let payment_event = {
3670                 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3671                 check_added_monitors!(nodes[0], 1);
3672
3673                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3674                 assert_eq!(events.len(), 1);
3675                 SendEvent::from_event(events.remove(0))
3676         };
3677         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3678
3679         if messages_delivered < 2 {
3680                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3681         } else {
3682                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3683                 if messages_delivered >= 3 {
3684                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3685                         check_added_monitors!(nodes[1], 1);
3686                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3687
3688                         if messages_delivered >= 4 {
3689                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3690                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3691                                 check_added_monitors!(nodes[0], 1);
3692
3693                                 if messages_delivered >= 5 {
3694                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3695                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3696                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3697                                         check_added_monitors!(nodes[0], 1);
3698
3699                                         if messages_delivered >= 6 {
3700                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3701                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3702                                                 check_added_monitors!(nodes[1], 1);
3703                                         }
3704                                 }
3705                         }
3706                 }
3707         }
3708
3709         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3710         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3711         if messages_delivered < 3 {
3712                 if simulate_broken_lnd {
3713                         // lnd has a long-standing bug where they send a channel_ready prior to a
3714                         // channel_reestablish if you reconnect prior to channel_ready time.
3715                         //
3716                         // Here we simulate that behavior, delivering a channel_ready immediately on
3717                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3718                         // in `reconnect_nodes` but we currently don't fail based on that.
3719                         //
3720                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3721                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3722                 }
3723                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3724                 // received on either side, both sides will need to resend them.
3725                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3726         } else if messages_delivered == 3 {
3727                 // nodes[0] still wants its RAA + commitment_signed
3728                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3729         } else if messages_delivered == 4 {
3730                 // nodes[0] still wants its commitment_signed
3731                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3732         } else if messages_delivered == 5 {
3733                 // nodes[1] still wants its final RAA
3734                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3735         } else if messages_delivered == 6 {
3736                 // Everything was delivered...
3737                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3738         }
3739
3740         let events_1 = nodes[1].node.get_and_clear_pending_events();
3741         if messages_delivered == 0 {
3742                 assert_eq!(events_1.len(), 2);
3743                 match events_1[0] {
3744                         Event::ChannelReady { .. } => { },
3745                         _ => panic!("Unexpected event"),
3746                 };
3747                 match events_1[1] {
3748                         Event::PendingHTLCsForwardable { .. } => { },
3749                         _ => panic!("Unexpected event"),
3750                 };
3751         } else {
3752                 assert_eq!(events_1.len(), 1);
3753                 match events_1[0] {
3754                         Event::PendingHTLCsForwardable { .. } => { },
3755                         _ => panic!("Unexpected event"),
3756                 };
3757         }
3758
3759         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3760         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3761         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3762
3763         nodes[1].node.process_pending_htlc_forwards();
3764
3765         let events_2 = nodes[1].node.get_and_clear_pending_events();
3766         assert_eq!(events_2.len(), 1);
3767         match events_2[0] {
3768                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
3769                         assert_eq!(payment_hash_1, *payment_hash);
3770                         assert_eq!(amount_msat, 1_000_000);
3771                         assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3772                         assert_eq!(via_channel_id, Some(channel_id));
3773                         match &purpose {
3774                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3775                                         assert!(payment_preimage.is_none());
3776                                         assert_eq!(payment_secret_1, *payment_secret);
3777                                 },
3778                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3779                         }
3780                 },
3781                 _ => panic!("Unexpected event"),
3782         }
3783
3784         nodes[1].node.claim_funds(payment_preimage_1);
3785         check_added_monitors!(nodes[1], 1);
3786         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3787
3788         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3789         assert_eq!(events_3.len(), 1);
3790         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3791                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3792                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3793                         assert!(updates.update_add_htlcs.is_empty());
3794                         assert!(updates.update_fail_htlcs.is_empty());
3795                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3796                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3797                         assert!(updates.update_fee.is_none());
3798                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3799                 },
3800                 _ => panic!("Unexpected event"),
3801         };
3802
3803         if messages_delivered >= 1 {
3804                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3805
3806                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3807                 assert_eq!(events_4.len(), 1);
3808                 match events_4[0] {
3809                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3810                                 assert_eq!(payment_preimage_1, *payment_preimage);
3811                                 assert_eq!(payment_hash_1, *payment_hash);
3812                         },
3813                         _ => panic!("Unexpected event"),
3814                 }
3815
3816                 if messages_delivered >= 2 {
3817                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3818                         check_added_monitors!(nodes[0], 1);
3819                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3820
3821                         if messages_delivered >= 3 {
3822                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3823                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3824                                 check_added_monitors!(nodes[1], 1);
3825
3826                                 if messages_delivered >= 4 {
3827                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3828                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3829                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3830                                         check_added_monitors!(nodes[1], 1);
3831
3832                                         if messages_delivered >= 5 {
3833                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3834                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3835                                                 check_added_monitors!(nodes[0], 1);
3836                                         }
3837                                 }
3838                         }
3839                 }
3840         }
3841
3842         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3843         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3844         if messages_delivered < 2 {
3845                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3846                 if messages_delivered < 1 {
3847                         expect_payment_sent!(nodes[0], payment_preimage_1);
3848                 } else {
3849                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3850                 }
3851         } else if messages_delivered == 2 {
3852                 // nodes[0] still wants its RAA + commitment_signed
3853                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3854         } else if messages_delivered == 3 {
3855                 // nodes[0] still wants its commitment_signed
3856                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3857         } else if messages_delivered == 4 {
3858                 // nodes[1] still wants its final RAA
3859                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3860         } else if messages_delivered == 5 {
3861                 // Everything was delivered...
3862                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3863         }
3864
3865         if messages_delivered == 1 || messages_delivered == 2 {
3866                 expect_payment_path_successful!(nodes[0]);
3867         }
3868         if messages_delivered <= 5 {
3869                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3870                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3871         }
3872         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3873
3874         if messages_delivered > 2 {
3875                 expect_payment_path_successful!(nodes[0]);
3876         }
3877
3878         // Channel should still work fine...
3879         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3880         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3881         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3882 }
3883
3884 #[test]
3885 fn test_drop_messages_peer_disconnect_a() {
3886         do_test_drop_messages_peer_disconnect(0, true);
3887         do_test_drop_messages_peer_disconnect(0, false);
3888         do_test_drop_messages_peer_disconnect(1, false);
3889         do_test_drop_messages_peer_disconnect(2, false);
3890 }
3891
3892 #[test]
3893 fn test_drop_messages_peer_disconnect_b() {
3894         do_test_drop_messages_peer_disconnect(3, false);
3895         do_test_drop_messages_peer_disconnect(4, false);
3896         do_test_drop_messages_peer_disconnect(5, false);
3897         do_test_drop_messages_peer_disconnect(6, false);
3898 }
3899
3900 #[test]
3901 fn test_channel_ready_without_best_block_updated() {
3902         // Previously, if we were offline when a funding transaction was locked in, and then we came
3903         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3904         // generate a channel_ready until a later best_block_updated. This tests that we generate the
3905         // channel_ready immediately instead.
3906         let chanmon_cfgs = create_chanmon_cfgs(2);
3907         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3908         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3909         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3910         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3911
3912         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
3913
3914         let conf_height = nodes[0].best_block_info().1 + 1;
3915         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3916         let block_txn = [funding_tx];
3917         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3918         let conf_block_header = nodes[0].get_block_header(conf_height);
3919         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3920
3921         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
3922         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
3923         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3924 }
3925
3926 #[test]
3927 fn test_drop_messages_peer_disconnect_dual_htlc() {
3928         // Test that we can handle reconnecting when both sides of a channel have pending
3929         // commitment_updates when we disconnect.
3930         let chanmon_cfgs = create_chanmon_cfgs(2);
3931         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3932         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3933         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3934         create_announced_chan_between_nodes(&nodes, 0, 1);
3935
3936         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3937
3938         // Now try to send a second payment which will fail to send
3939         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3940         nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
3941         check_added_monitors!(nodes[0], 1);
3942
3943         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3944         assert_eq!(events_1.len(), 1);
3945         match events_1[0] {
3946                 MessageSendEvent::UpdateHTLCs { .. } => {},
3947                 _ => panic!("Unexpected event"),
3948         }
3949
3950         nodes[1].node.claim_funds(payment_preimage_1);
3951         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3952         check_added_monitors!(nodes[1], 1);
3953
3954         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3955         assert_eq!(events_2.len(), 1);
3956         match events_2[0] {
3957                 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 } } => {
3958                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3959                         assert!(update_add_htlcs.is_empty());
3960                         assert_eq!(update_fulfill_htlcs.len(), 1);
3961                         assert!(update_fail_htlcs.is_empty());
3962                         assert!(update_fail_malformed_htlcs.is_empty());
3963                         assert!(update_fee.is_none());
3964
3965                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3966                         let events_3 = nodes[0].node.get_and_clear_pending_events();
3967                         assert_eq!(events_3.len(), 1);
3968                         match events_3[0] {
3969                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3970                                         assert_eq!(*payment_preimage, payment_preimage_1);
3971                                         assert_eq!(*payment_hash, payment_hash_1);
3972                                 },
3973                                 _ => panic!("Unexpected event"),
3974                         }
3975
3976                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3977                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3978                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3979                         check_added_monitors!(nodes[0], 1);
3980                 },
3981                 _ => panic!("Unexpected event"),
3982         }
3983
3984         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3985         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3986
3987         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();
3988         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3989         assert_eq!(reestablish_1.len(), 1);
3990         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();
3991         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3992         assert_eq!(reestablish_2.len(), 1);
3993
3994         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3995         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3996         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3997         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3998
3999         assert!(as_resp.0.is_none());
4000         assert!(bs_resp.0.is_none());
4001
4002         assert!(bs_resp.1.is_none());
4003         assert!(bs_resp.2.is_none());
4004
4005         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4006
4007         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4008         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4009         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4010         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4011         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4012         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4013         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4014         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4015         // No commitment_signed so get_event_msg's assert(len == 1) passes
4016         check_added_monitors!(nodes[1], 1);
4017
4018         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4019         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4020         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4021         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4022         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4023         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4024         assert!(bs_second_commitment_signed.update_fee.is_none());
4025         check_added_monitors!(nodes[1], 1);
4026
4027         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4028         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4029         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4030         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4031         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4032         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4033         assert!(as_commitment_signed.update_fee.is_none());
4034         check_added_monitors!(nodes[0], 1);
4035
4036         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4037         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4038         // No commitment_signed so get_event_msg's assert(len == 1) passes
4039         check_added_monitors!(nodes[0], 1);
4040
4041         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4042         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4043         // No commitment_signed so get_event_msg's assert(len == 1) passes
4044         check_added_monitors!(nodes[1], 1);
4045
4046         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4047         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4048         check_added_monitors!(nodes[1], 1);
4049
4050         expect_pending_htlcs_forwardable!(nodes[1]);
4051
4052         let events_5 = nodes[1].node.get_and_clear_pending_events();
4053         assert_eq!(events_5.len(), 1);
4054         match events_5[0] {
4055                 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4056                         assert_eq!(payment_hash_2, *payment_hash);
4057                         match &purpose {
4058                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4059                                         assert!(payment_preimage.is_none());
4060                                         assert_eq!(payment_secret_2, *payment_secret);
4061                                 },
4062                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4063                         }
4064                 },
4065                 _ => panic!("Unexpected event"),
4066         }
4067
4068         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4069         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4070         check_added_monitors!(nodes[0], 1);
4071
4072         expect_payment_path_successful!(nodes[0]);
4073         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4074 }
4075
4076 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4077         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4078         // to avoid our counterparty failing the channel.
4079         let chanmon_cfgs = create_chanmon_cfgs(2);
4080         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4081         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4082         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4083
4084         create_announced_chan_between_nodes(&nodes, 0, 1);
4085
4086         let our_payment_hash = if send_partial_mpp {
4087                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4088                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4089                 // indicates there are more HTLCs coming.
4090                 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.
4091                 let payment_id = PaymentId([42; 32]);
4092                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(payment_secret), payment_id, &route).unwrap();
4093                 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[0]).unwrap();
4094                 check_added_monitors!(nodes[0], 1);
4095                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4096                 assert_eq!(events.len(), 1);
4097                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4098                 // hop should *not* yet generate any PaymentClaimable event(s).
4099                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4100                 our_payment_hash
4101         } else {
4102                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4103         };
4104
4105         let mut block = Block {
4106                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
4107                 txdata: vec![],
4108         };
4109         connect_block(&nodes[0], &block);
4110         connect_block(&nodes[1], &block);
4111         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4112         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4113                 block.header.prev_blockhash = block.block_hash();
4114                 connect_block(&nodes[0], &block);
4115                 connect_block(&nodes[1], &block);
4116         }
4117
4118         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4119
4120         check_added_monitors!(nodes[1], 1);
4121         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4122         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4123         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4124         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4125         assert!(htlc_timeout_updates.update_fee.is_none());
4126
4127         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4128         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4129         // 100_000 msat as u64, followed by the height at which we failed back above
4130         let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4131         expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4132         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4133 }
4134
4135 #[test]
4136 fn test_htlc_timeout() {
4137         do_test_htlc_timeout(true);
4138         do_test_htlc_timeout(false);
4139 }
4140
4141 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4142         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4143         let chanmon_cfgs = create_chanmon_cfgs(3);
4144         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4145         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4146         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4147         create_announced_chan_between_nodes(&nodes, 0, 1);
4148         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4149
4150         // Make sure all nodes are at the same starting height
4151         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4152         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4153         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4154
4155         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4156         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4157         {
4158                 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4159         }
4160         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4161         check_added_monitors!(nodes[1], 1);
4162
4163         // Now attempt to route a second payment, which should be placed in the holding cell
4164         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4165         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4166         sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4167         if forwarded_htlc {
4168                 check_added_monitors!(nodes[0], 1);
4169                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4170                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4171                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4172                 expect_pending_htlcs_forwardable!(nodes[1]);
4173         }
4174         check_added_monitors!(nodes[1], 0);
4175
4176         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4177         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4178         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4179         connect_blocks(&nodes[1], 1);
4180
4181         if forwarded_htlc {
4182                 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 }]);
4183                 check_added_monitors!(nodes[1], 1);
4184                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4185                 assert_eq!(fail_commit.len(), 1);
4186                 match fail_commit[0] {
4187                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4188                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4189                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4190                         },
4191                         _ => unreachable!(),
4192                 }
4193                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4194         } else {
4195                 expect_payment_failed!(nodes[1], second_payment_hash, false);
4196         }
4197 }
4198
4199 #[test]
4200 fn test_holding_cell_htlc_add_timeouts() {
4201         do_test_holding_cell_htlc_add_timeouts(false);
4202         do_test_holding_cell_htlc_add_timeouts(true);
4203 }
4204
4205 macro_rules! check_spendable_outputs {
4206         ($node: expr, $keysinterface: expr) => {
4207                 {
4208                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4209                         let mut txn = Vec::new();
4210                         let mut all_outputs = Vec::new();
4211                         let secp_ctx = Secp256k1::new();
4212                         for event in events.drain(..) {
4213                                 match event {
4214                                         Event::SpendableOutputs { mut outputs } => {
4215                                                 for outp in outputs.drain(..) {
4216                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4217                                                         all_outputs.push(outp);
4218                                                 }
4219                                         },
4220                                         _ => panic!("Unexpected event"),
4221                                 };
4222                         }
4223                         if all_outputs.len() > 1 {
4224                                 if let Ok(tx) = $keysinterface.backing.spend_spendable_outputs(&all_outputs.iter().map(|a| a).collect::<Vec<_>>(), Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx) {
4225                                         txn.push(tx);
4226                                 }
4227                         }
4228                         txn
4229                 }
4230         }
4231 }
4232
4233 #[test]
4234 fn test_claim_sizeable_push_msat() {
4235         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4236         let chanmon_cfgs = create_chanmon_cfgs(2);
4237         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4238         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4239         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4240
4241         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4242         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4243         check_closed_broadcast!(nodes[1], true);
4244         check_added_monitors!(nodes[1], 1);
4245         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4246         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4247         assert_eq!(node_txn.len(), 1);
4248         check_spends!(node_txn[0], chan.3);
4249         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
4250
4251         mine_transaction(&nodes[1], &node_txn[0]);
4252         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4253
4254         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4255         assert_eq!(spend_txn.len(), 1);
4256         assert_eq!(spend_txn[0].input.len(), 1);
4257         check_spends!(spend_txn[0], node_txn[0]);
4258         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4259 }
4260
4261 #[test]
4262 fn test_claim_on_remote_sizeable_push_msat() {
4263         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4264         // to_remote output is encumbered by a P2WPKH
4265         let chanmon_cfgs = create_chanmon_cfgs(2);
4266         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4267         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4268         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4269
4270         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4271         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4272         check_closed_broadcast!(nodes[0], true);
4273         check_added_monitors!(nodes[0], 1);
4274         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4275
4276         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4277         assert_eq!(node_txn.len(), 1);
4278         check_spends!(node_txn[0], chan.3);
4279         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
4280
4281         mine_transaction(&nodes[1], &node_txn[0]);
4282         check_closed_broadcast!(nodes[1], true);
4283         check_added_monitors!(nodes[1], 1);
4284         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4285         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4286
4287         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4288         assert_eq!(spend_txn.len(), 1);
4289         check_spends!(spend_txn[0], node_txn[0]);
4290 }
4291
4292 #[test]
4293 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4294         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4295         // to_remote output is encumbered by a P2WPKH
4296
4297         let chanmon_cfgs = create_chanmon_cfgs(2);
4298         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4299         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4300         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4301
4302         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4303         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4304         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4305         assert_eq!(revoked_local_txn[0].input.len(), 1);
4306         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4307
4308         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4309         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4310         check_closed_broadcast!(nodes[1], true);
4311         check_added_monitors!(nodes[1], 1);
4312         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4313
4314         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4315         mine_transaction(&nodes[1], &node_txn[0]);
4316         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4317
4318         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4319         assert_eq!(spend_txn.len(), 3);
4320         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4321         check_spends!(spend_txn[1], node_txn[0]);
4322         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4323 }
4324
4325 #[test]
4326 fn test_static_spendable_outputs_preimage_tx() {
4327         let chanmon_cfgs = create_chanmon_cfgs(2);
4328         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4329         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4330         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4331
4332         // Create some initial channels
4333         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4334
4335         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4336
4337         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4338         assert_eq!(commitment_tx[0].input.len(), 1);
4339         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4340
4341         // Settle A's commitment tx on B's chain
4342         nodes[1].node.claim_funds(payment_preimage);
4343         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4344         check_added_monitors!(nodes[1], 1);
4345         mine_transaction(&nodes[1], &commitment_tx[0]);
4346         check_added_monitors!(nodes[1], 1);
4347         let events = nodes[1].node.get_and_clear_pending_msg_events();
4348         match events[0] {
4349                 MessageSendEvent::UpdateHTLCs { .. } => {},
4350                 _ => panic!("Unexpected event"),
4351         }
4352         match events[1] {
4353                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4354                 _ => panic!("Unexepected event"),
4355         }
4356
4357         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4358         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4359         assert_eq!(node_txn.len(), 1);
4360         check_spends!(node_txn[0], commitment_tx[0]);
4361         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4362
4363         mine_transaction(&nodes[1], &node_txn[0]);
4364         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4365         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4366
4367         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4368         assert_eq!(spend_txn.len(), 1);
4369         check_spends!(spend_txn[0], node_txn[0]);
4370 }
4371
4372 #[test]
4373 fn test_static_spendable_outputs_timeout_tx() {
4374         let chanmon_cfgs = create_chanmon_cfgs(2);
4375         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4376         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4377         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4378
4379         // Create some initial channels
4380         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4381
4382         // Rebalance the network a bit by relaying one payment through all the channels ...
4383         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4384
4385         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 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' chain
4392         mine_transaction(&nodes[1], &commitment_tx[0]);
4393         check_added_monitors!(nodes[1], 1);
4394         let events = nodes[1].node.get_and_clear_pending_msg_events();
4395         match events[0] {
4396                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4397                 _ => panic!("Unexpected event"),
4398         }
4399         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4400
4401         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4402         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4403         assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4404         check_spends!(node_txn[0],  commitment_tx[0].clone());
4405         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4406
4407         mine_transaction(&nodes[1], &node_txn[0]);
4408         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4409         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4410         expect_payment_failed!(nodes[1], our_payment_hash, false);
4411
4412         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4413         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4414         check_spends!(spend_txn[0], commitment_tx[0]);
4415         check_spends!(spend_txn[1], node_txn[0]);
4416         check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4417 }
4418
4419 #[test]
4420 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4421         let chanmon_cfgs = create_chanmon_cfgs(2);
4422         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4423         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4424         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4425
4426         // Create some initial channels
4427         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4428
4429         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4430         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4431         assert_eq!(revoked_local_txn[0].input.len(), 1);
4432         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4433
4434         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4435
4436         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4437         check_closed_broadcast!(nodes[1], true);
4438         check_added_monitors!(nodes[1], 1);
4439         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4440
4441         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4442         assert_eq!(node_txn.len(), 1);
4443         assert_eq!(node_txn[0].input.len(), 2);
4444         check_spends!(node_txn[0], revoked_local_txn[0]);
4445
4446         mine_transaction(&nodes[1], &node_txn[0]);
4447         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4448
4449         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4450         assert_eq!(spend_txn.len(), 1);
4451         check_spends!(spend_txn[0], node_txn[0]);
4452 }
4453
4454 #[test]
4455 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4456         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4457         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4458         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4459         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4460         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4461
4462         // Create some initial channels
4463         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4464
4465         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4466         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4467         assert_eq!(revoked_local_txn[0].input.len(), 1);
4468         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4469
4470         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4471
4472         // A will generate HTLC-Timeout from revoked commitment tx
4473         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4474         check_closed_broadcast!(nodes[0], true);
4475         check_added_monitors!(nodes[0], 1);
4476         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4477         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4478
4479         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4480         assert_eq!(revoked_htlc_txn.len(), 1);
4481         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4482         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4483         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4484         assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4485
4486         // B will generate justice tx from A's revoked commitment/HTLC tx
4487         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4488         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4489         check_closed_broadcast!(nodes[1], true);
4490         check_added_monitors!(nodes[1], 1);
4491         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4492
4493         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4494         assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4495         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4496         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4497         // transactions next...
4498         assert_eq!(node_txn[0].input.len(), 3);
4499         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4500
4501         assert_eq!(node_txn[1].input.len(), 2);
4502         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4503         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4504                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4505         } else {
4506                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4507                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4508         }
4509
4510         mine_transaction(&nodes[1], &node_txn[1]);
4511         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4512
4513         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4514         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4515         assert_eq!(spend_txn.len(), 1);
4516         assert_eq!(spend_txn[0].input.len(), 1);
4517         check_spends!(spend_txn[0], node_txn[1]);
4518 }
4519
4520 #[test]
4521 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4522         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4523         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4524         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4525         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4526         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4527
4528         // Create some initial channels
4529         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4530
4531         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4532         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4533         assert_eq!(revoked_local_txn[0].input.len(), 1);
4534         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4535
4536         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4537         assert_eq!(revoked_local_txn[0].output.len(), 2);
4538
4539         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4540
4541         // B will generate HTLC-Success from revoked commitment tx
4542         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4543         check_closed_broadcast!(nodes[1], true);
4544         check_added_monitors!(nodes[1], 1);
4545         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4546         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4547
4548         assert_eq!(revoked_htlc_txn.len(), 1);
4549         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4550         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4551         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4552
4553         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4554         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4555         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4556
4557         // A will generate justice tx from B's revoked commitment/HTLC tx
4558         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4559         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4560         check_closed_broadcast!(nodes[0], true);
4561         check_added_monitors!(nodes[0], 1);
4562         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4563
4564         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4565         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4566
4567         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4568         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4569         // transactions next...
4570         assert_eq!(node_txn[0].input.len(), 2);
4571         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4572         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4573                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4574         } else {
4575                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4576                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4577         }
4578
4579         assert_eq!(node_txn[1].input.len(), 1);
4580         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4581
4582         mine_transaction(&nodes[0], &node_txn[1]);
4583         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4584
4585         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4586         // didn't try to generate any new transactions.
4587
4588         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4589         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4590         assert_eq!(spend_txn.len(), 3);
4591         assert_eq!(spend_txn[0].input.len(), 1);
4592         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4593         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4594         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4595         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4596 }
4597
4598 #[test]
4599 fn test_onchain_to_onchain_claim() {
4600         // Test that in case of channel closure, we detect the state of output and claim HTLC
4601         // on downstream peer's remote commitment tx.
4602         // First, have C claim an HTLC against its own latest commitment transaction.
4603         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4604         // channel.
4605         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4606         // gets broadcast.
4607
4608         let chanmon_cfgs = create_chanmon_cfgs(3);
4609         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4610         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4611         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4612
4613         // Create some initial channels
4614         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4615         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4616
4617         // Ensure all nodes are at the same height
4618         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4619         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4620         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4621         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4622
4623         // Rebalance the network a bit by relaying one payment through all the channels ...
4624         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4625         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4626
4627         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4628         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4629         check_spends!(commitment_tx[0], chan_2.3);
4630         nodes[2].node.claim_funds(payment_preimage);
4631         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4632         check_added_monitors!(nodes[2], 1);
4633         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4634         assert!(updates.update_add_htlcs.is_empty());
4635         assert!(updates.update_fail_htlcs.is_empty());
4636         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4637         assert!(updates.update_fail_malformed_htlcs.is_empty());
4638
4639         mine_transaction(&nodes[2], &commitment_tx[0]);
4640         check_closed_broadcast!(nodes[2], true);
4641         check_added_monitors!(nodes[2], 1);
4642         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4643
4644         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4645         assert_eq!(c_txn.len(), 1);
4646         check_spends!(c_txn[0], commitment_tx[0]);
4647         assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4648         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4649         assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4650
4651         // 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
4652         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
4653         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone(), c_txn[0].clone()]});
4654         check_added_monitors!(nodes[1], 1);
4655         let events = nodes[1].node.get_and_clear_pending_events();
4656         assert_eq!(events.len(), 2);
4657         match events[0] {
4658                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4659                 _ => panic!("Unexpected event"),
4660         }
4661         match events[1] {
4662                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4663                         assert_eq!(fee_earned_msat, Some(1000));
4664                         assert_eq!(prev_channel_id, Some(chan_1.2));
4665                         assert_eq!(claim_from_onchain_tx, true);
4666                         assert_eq!(next_channel_id, Some(chan_2.2));
4667                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4668                 },
4669                 _ => panic!("Unexpected event"),
4670         }
4671         check_added_monitors!(nodes[1], 1);
4672         let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4673         assert_eq!(msg_events.len(), 3);
4674         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4675         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4676
4677         match nodes_2_event {
4678                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4679                 _ => panic!("Unexpected event"),
4680         }
4681
4682         match nodes_0_event {
4683                 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, .. } } => {
4684                         assert!(update_add_htlcs.is_empty());
4685                         assert!(update_fail_htlcs.is_empty());
4686                         assert_eq!(update_fulfill_htlcs.len(), 1);
4687                         assert!(update_fail_malformed_htlcs.is_empty());
4688                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4689                 },
4690                 _ => panic!("Unexpected event"),
4691         };
4692
4693         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4694         match msg_events[0] {
4695                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4696                 _ => panic!("Unexpected event"),
4697         }
4698
4699         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4700         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4701         mine_transaction(&nodes[1], &commitment_tx[0]);
4702         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4703         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4704         // ChannelMonitor: HTLC-Success tx
4705         assert_eq!(b_txn.len(), 1);
4706         check_spends!(b_txn[0], commitment_tx[0]);
4707         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4708         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4709         assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1 + 1); // Success tx
4710
4711         check_closed_broadcast!(nodes[1], true);
4712         check_added_monitors!(nodes[1], 1);
4713 }
4714
4715 #[test]
4716 fn test_duplicate_payment_hash_one_failure_one_success() {
4717         // Topology : A --> B --> C --> D
4718         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4719         // Note that because C will refuse to generate two payment secrets for the same payment hash,
4720         // we forward one of the payments onwards to D.
4721         let chanmon_cfgs = create_chanmon_cfgs(4);
4722         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4723         // When this test was written, the default base fee floated based on the HTLC count.
4724         // It is now fixed, so we simply set the fee to the expected value here.
4725         let mut config = test_default_channel_config();
4726         config.channel_config.forwarding_fee_base_msat = 196;
4727         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4728                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4729         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4730
4731         create_announced_chan_between_nodes(&nodes, 0, 1);
4732         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4733         create_announced_chan_between_nodes(&nodes, 2, 3);
4734
4735         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4736         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4737         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4738         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4739         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4740
4741         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4742
4743         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4744         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4745         // script push size limit so that the below script length checks match
4746         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4747         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4748                 .with_features(nodes[3].node.invoice_features());
4749         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000, TEST_FINAL_CLTV - 40);
4750         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4751
4752         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4753         assert_eq!(commitment_txn[0].input.len(), 1);
4754         check_spends!(commitment_txn[0], chan_2.3);
4755
4756         mine_transaction(&nodes[1], &commitment_txn[0]);
4757         check_closed_broadcast!(nodes[1], true);
4758         check_added_monitors!(nodes[1], 1);
4759         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4760         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
4761
4762         let htlc_timeout_tx;
4763         { // Extract one of the two HTLC-Timeout transaction
4764                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4765                 // ChannelMonitor: timeout tx * 2-or-3
4766                 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4767
4768                 check_spends!(node_txn[0], commitment_txn[0]);
4769                 assert_eq!(node_txn[0].input.len(), 1);
4770                 assert_eq!(node_txn[0].output.len(), 1);
4771
4772                 if node_txn.len() > 2 {
4773                         check_spends!(node_txn[1], commitment_txn[0]);
4774                         assert_eq!(node_txn[1].input.len(), 1);
4775                         assert_eq!(node_txn[1].output.len(), 1);
4776                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4777
4778                         check_spends!(node_txn[2], commitment_txn[0]);
4779                         assert_eq!(node_txn[2].input.len(), 1);
4780                         assert_eq!(node_txn[2].output.len(), 1);
4781                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4782                 } else {
4783                         check_spends!(node_txn[1], commitment_txn[0]);
4784                         assert_eq!(node_txn[1].input.len(), 1);
4785                         assert_eq!(node_txn[1].output.len(), 1);
4786                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4787                 }
4788
4789                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4790                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4791                 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
4792                 // (with value 900 sats) will be claimed in the below `claim_funds` call.
4793                 if node_txn.len() > 2 {
4794                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4795                         htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
4796                 } else {
4797                         htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
4798                 }
4799         }
4800
4801         nodes[2].node.claim_funds(our_payment_preimage);
4802         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4803
4804         mine_transaction(&nodes[2], &commitment_txn[0]);
4805         check_added_monitors!(nodes[2], 2);
4806         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4807         let events = nodes[2].node.get_and_clear_pending_msg_events();
4808         match events[0] {
4809                 MessageSendEvent::UpdateHTLCs { .. } => {},
4810                 _ => panic!("Unexpected event"),
4811         }
4812         match events[1] {
4813                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4814                 _ => panic!("Unexepected event"),
4815         }
4816         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4817         assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4818         check_spends!(htlc_success_txn[0], commitment_txn[0]);
4819         check_spends!(htlc_success_txn[1], commitment_txn[0]);
4820         assert_eq!(htlc_success_txn[0].input.len(), 1);
4821         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4822         assert_eq!(htlc_success_txn[1].input.len(), 1);
4823         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4824         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4825         assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4826
4827         mine_transaction(&nodes[1], &htlc_timeout_tx);
4828         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4829         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 }]);
4830         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4831         assert!(htlc_updates.update_add_htlcs.is_empty());
4832         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4833         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4834         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4835         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4836         check_added_monitors!(nodes[1], 1);
4837
4838         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4839         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4840         {
4841                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4842         }
4843         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
4844
4845         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4846         mine_transaction(&nodes[1], &htlc_success_txn[1]);
4847         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
4848         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4849         assert!(updates.update_add_htlcs.is_empty());
4850         assert!(updates.update_fail_htlcs.is_empty());
4851         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4852         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
4853         assert!(updates.update_fail_malformed_htlcs.is_empty());
4854         check_added_monitors!(nodes[1], 1);
4855
4856         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4857         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4858
4859         let events = nodes[0].node.get_and_clear_pending_events();
4860         match events[0] {
4861                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4862                         assert_eq!(*payment_preimage, our_payment_preimage);
4863                         assert_eq!(*payment_hash, duplicate_payment_hash);
4864                 }
4865                 _ => panic!("Unexpected event"),
4866         }
4867 }
4868
4869 #[test]
4870 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4871         let chanmon_cfgs = create_chanmon_cfgs(2);
4872         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4873         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4874         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4875
4876         // Create some initial channels
4877         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4878
4879         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
4880         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4881         assert_eq!(local_txn.len(), 1);
4882         assert_eq!(local_txn[0].input.len(), 1);
4883         check_spends!(local_txn[0], chan_1.3);
4884
4885         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4886         nodes[1].node.claim_funds(payment_preimage);
4887         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
4888         check_added_monitors!(nodes[1], 1);
4889
4890         mine_transaction(&nodes[1], &local_txn[0]);
4891         check_added_monitors!(nodes[1], 1);
4892         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4893         let events = nodes[1].node.get_and_clear_pending_msg_events();
4894         match events[0] {
4895                 MessageSendEvent::UpdateHTLCs { .. } => {},
4896                 _ => panic!("Unexpected event"),
4897         }
4898         match events[1] {
4899                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4900                 _ => panic!("Unexepected event"),
4901         }
4902         let node_tx = {
4903                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4904                 assert_eq!(node_txn.len(), 1);
4905                 assert_eq!(node_txn[0].input.len(), 1);
4906                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4907                 check_spends!(node_txn[0], local_txn[0]);
4908                 node_txn[0].clone()
4909         };
4910
4911         mine_transaction(&nodes[1], &node_tx);
4912         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4913
4914         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4915         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4916         assert_eq!(spend_txn.len(), 1);
4917         assert_eq!(spend_txn[0].input.len(), 1);
4918         check_spends!(spend_txn[0], node_tx);
4919         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4920 }
4921
4922 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4923         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4924         // unrevoked commitment transaction.
4925         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4926         // a remote RAA before they could be failed backwards (and combinations thereof).
4927         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4928         // use the same payment hashes.
4929         // Thus, we use a six-node network:
4930         //
4931         // A \         / E
4932         //    - C - D -
4933         // B /         \ F
4934         // And test where C fails back to A/B when D announces its latest commitment transaction
4935         let chanmon_cfgs = create_chanmon_cfgs(6);
4936         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4937         // When this test was written, the default base fee floated based on the HTLC count.
4938         // It is now fixed, so we simply set the fee to the expected value here.
4939         let mut config = test_default_channel_config();
4940         config.channel_config.forwarding_fee_base_msat = 196;
4941         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
4942                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4943         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4944
4945         let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
4946         let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4947         let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
4948         let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
4949         let chan_3_5  = create_announced_chan_between_nodes(&nodes, 3, 5);
4950
4951         // Rebalance and check output sanity...
4952         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
4953         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
4954         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
4955
4956         let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
4957                 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
4958         // 0th HTLC:
4959         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
4960         // 1st HTLC:
4961         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
4962         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4963         // 2nd HTLC:
4964         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
4965         // 3rd HTLC:
4966         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
4967         // 4th HTLC:
4968         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4969         // 5th HTLC:
4970         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4971         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
4972         // 6th HTLC:
4973         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());
4974         // 7th HTLC:
4975         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());
4976
4977         // 8th HTLC:
4978         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4979         // 9th HTLC:
4980         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4981         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
4982
4983         // 10th HTLC:
4984         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
4985         // 11th HTLC:
4986         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
4987         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());
4988
4989         // Double-check that six of the new HTLC were added
4990         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
4991         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
4992         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
4993         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
4994
4995         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
4996         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
4997         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
4998         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
4999         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5000         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5001         check_added_monitors!(nodes[4], 0);
5002
5003         let failed_destinations = vec![
5004                 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5005                 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5006                 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5007                 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5008         ];
5009         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5010         check_added_monitors!(nodes[4], 1);
5011
5012         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5013         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5014         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5015         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5016         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5017         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5018
5019         // Fail 3rd below-dust and 7th above-dust HTLCs
5020         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5021         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5022         check_added_monitors!(nodes[5], 0);
5023
5024         let failed_destinations_2 = vec![
5025                 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5026                 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5027         ];
5028         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5029         check_added_monitors!(nodes[5], 1);
5030
5031         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5032         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5033         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5034         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5035
5036         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5037
5038         // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5039         let failed_destinations_3 = vec![
5040                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5041                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5042                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5043                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5044                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5045                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5046         ];
5047         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5048         check_added_monitors!(nodes[3], 1);
5049         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5050         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5051         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5052         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5053         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5054         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5055         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5056         if deliver_last_raa {
5057                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5058         } else {
5059                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5060         }
5061
5062         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5063         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5064         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5065         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5066         //
5067         // We now broadcast the latest commitment transaction, which *should* result in failures for
5068         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5069         // the non-broadcast above-dust HTLCs.
5070         //
5071         // Alternatively, we may broadcast the previous commitment transaction, which should only
5072         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5073         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5074
5075         if announce_latest {
5076                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5077         } else {
5078                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5079         }
5080         let events = nodes[2].node.get_and_clear_pending_events();
5081         let close_event = if deliver_last_raa {
5082                 assert_eq!(events.len(), 2 + 6);
5083                 events.last().clone().unwrap()
5084         } else {
5085                 assert_eq!(events.len(), 1);
5086                 events.last().clone().unwrap()
5087         };
5088         match close_event {
5089                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5090                 _ => panic!("Unexpected event"),
5091         }
5092
5093         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5094         check_closed_broadcast!(nodes[2], true);
5095         if deliver_last_raa {
5096                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5097
5098                 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();
5099                 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5100         } else {
5101                 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5102                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5103                 } else {
5104                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5105                 };
5106
5107                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5108         }
5109         check_added_monitors!(nodes[2], 3);
5110
5111         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5112         assert_eq!(cs_msgs.len(), 2);
5113         let mut a_done = false;
5114         for msg in cs_msgs {
5115                 match msg {
5116                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5117                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5118                                 // should be failed-backwards here.
5119                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5120                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5121                                         for htlc in &updates.update_fail_htlcs {
5122                                                 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 });
5123                                         }
5124                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5125                                         assert!(!a_done);
5126                                         a_done = true;
5127                                         &nodes[0]
5128                                 } else {
5129                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5130                                         for htlc in &updates.update_fail_htlcs {
5131                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5132                                         }
5133                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5134                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5135                                         &nodes[1]
5136                                 };
5137                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5138                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5139                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5140                                 if announce_latest {
5141                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5142                                         if *node_id == nodes[0].node.get_our_node_id() {
5143                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5144                                         }
5145                                 }
5146                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5147                         },
5148                         _ => panic!("Unexpected event"),
5149                 }
5150         }
5151
5152         let as_events = nodes[0].node.get_and_clear_pending_events();
5153         assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5154         let mut as_failds = HashSet::new();
5155         let mut as_updates = 0;
5156         for event in as_events.iter() {
5157                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5158                         assert!(as_failds.insert(*payment_hash));
5159                         if *payment_hash != payment_hash_2 {
5160                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5161                         } else {
5162                                 assert!(!payment_failed_permanently);
5163                         }
5164                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5165                                 as_updates += 1;
5166                         }
5167                 } else if let &Event::PaymentFailed { .. } = event {
5168                 } else { panic!("Unexpected event"); }
5169         }
5170         assert!(as_failds.contains(&payment_hash_1));
5171         assert!(as_failds.contains(&payment_hash_2));
5172         if announce_latest {
5173                 assert!(as_failds.contains(&payment_hash_3));
5174                 assert!(as_failds.contains(&payment_hash_5));
5175         }
5176         assert!(as_failds.contains(&payment_hash_6));
5177
5178         let bs_events = nodes[1].node.get_and_clear_pending_events();
5179         assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5180         let mut bs_failds = HashSet::new();
5181         let mut bs_updates = 0;
5182         for event in bs_events.iter() {
5183                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5184                         assert!(bs_failds.insert(*payment_hash));
5185                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5186                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5187                         } else {
5188                                 assert!(!payment_failed_permanently);
5189                         }
5190                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5191                                 bs_updates += 1;
5192                         }
5193                 } else if let &Event::PaymentFailed { .. } = event {
5194                 } else { panic!("Unexpected event"); }
5195         }
5196         assert!(bs_failds.contains(&payment_hash_1));
5197         assert!(bs_failds.contains(&payment_hash_2));
5198         if announce_latest {
5199                 assert!(bs_failds.contains(&payment_hash_4));
5200         }
5201         assert!(bs_failds.contains(&payment_hash_5));
5202
5203         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5204         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5205         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5206         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5207         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5208         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5209 }
5210
5211 #[test]
5212 fn test_fail_backwards_latest_remote_announce_a() {
5213         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5214 }
5215
5216 #[test]
5217 fn test_fail_backwards_latest_remote_announce_b() {
5218         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5219 }
5220
5221 #[test]
5222 fn test_fail_backwards_previous_remote_announce() {
5223         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5224         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5225         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5226 }
5227
5228 #[test]
5229 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5230         let chanmon_cfgs = create_chanmon_cfgs(2);
5231         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5232         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5233         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5234
5235         // Create some initial channels
5236         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5237
5238         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5239         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5240         assert_eq!(local_txn[0].input.len(), 1);
5241         check_spends!(local_txn[0], chan_1.3);
5242
5243         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5244         mine_transaction(&nodes[0], &local_txn[0]);
5245         check_closed_broadcast!(nodes[0], true);
5246         check_added_monitors!(nodes[0], 1);
5247         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5248         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5249
5250         let htlc_timeout = {
5251                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5252                 assert_eq!(node_txn.len(), 1);
5253                 assert_eq!(node_txn[0].input.len(), 1);
5254                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5255                 check_spends!(node_txn[0], local_txn[0]);
5256                 node_txn[0].clone()
5257         };
5258
5259         mine_transaction(&nodes[0], &htlc_timeout);
5260         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5261         expect_payment_failed!(nodes[0], our_payment_hash, false);
5262
5263         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5264         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5265         assert_eq!(spend_txn.len(), 3);
5266         check_spends!(spend_txn[0], local_txn[0]);
5267         assert_eq!(spend_txn[1].input.len(), 1);
5268         check_spends!(spend_txn[1], htlc_timeout);
5269         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5270         assert_eq!(spend_txn[2].input.len(), 2);
5271         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5272         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5273                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5274 }
5275
5276 #[test]
5277 fn test_key_derivation_params() {
5278         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5279         // manager rotation to test that `channel_keys_id` returned in
5280         // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5281         // then derive a `delayed_payment_key`.
5282
5283         let chanmon_cfgs = create_chanmon_cfgs(3);
5284
5285         // We manually create the node configuration to backup the seed.
5286         let seed = [42; 32];
5287         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5288         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);
5289         let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5290         let scorer = Mutex::new(test_utils::TestScorer::new());
5291         let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5292         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)) };
5293         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5294         node_cfgs.remove(0);
5295         node_cfgs.insert(0, node);
5296
5297         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5298         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5299
5300         // Create some initial channels
5301         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5302         // for node 0
5303         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5304         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5305         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5306
5307         // Ensure all nodes are at the same height
5308         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5309         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5310         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5311         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5312
5313         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5314         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5315         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5316         assert_eq!(local_txn_1[0].input.len(), 1);
5317         check_spends!(local_txn_1[0], chan_1.3);
5318
5319         // We check funding pubkey are unique
5320         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]));
5321         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]));
5322         if from_0_funding_key_0 == from_1_funding_key_0
5323             || from_0_funding_key_0 == from_1_funding_key_1
5324             || from_0_funding_key_1 == from_1_funding_key_0
5325             || from_0_funding_key_1 == from_1_funding_key_1 {
5326                 panic!("Funding pubkeys aren't unique");
5327         }
5328
5329         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5330         mine_transaction(&nodes[0], &local_txn_1[0]);
5331         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5332         check_closed_broadcast!(nodes[0], true);
5333         check_added_monitors!(nodes[0], 1);
5334         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5335
5336         let htlc_timeout = {
5337                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5338                 assert_eq!(node_txn.len(), 1);
5339                 assert_eq!(node_txn[0].input.len(), 1);
5340                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5341                 check_spends!(node_txn[0], local_txn_1[0]);
5342                 node_txn[0].clone()
5343         };
5344
5345         mine_transaction(&nodes[0], &htlc_timeout);
5346         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5347         expect_payment_failed!(nodes[0], our_payment_hash, false);
5348
5349         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5350         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5351         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5352         assert_eq!(spend_txn.len(), 3);
5353         check_spends!(spend_txn[0], local_txn_1[0]);
5354         assert_eq!(spend_txn[1].input.len(), 1);
5355         check_spends!(spend_txn[1], htlc_timeout);
5356         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5357         assert_eq!(spend_txn[2].input.len(), 2);
5358         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5359         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5360                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5361 }
5362
5363 #[test]
5364 fn test_static_output_closing_tx() {
5365         let chanmon_cfgs = create_chanmon_cfgs(2);
5366         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5367         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5368         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5369
5370         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5371
5372         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5373         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5374
5375         mine_transaction(&nodes[0], &closing_tx);
5376         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5377         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5378
5379         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5380         assert_eq!(spend_txn.len(), 1);
5381         check_spends!(spend_txn[0], closing_tx);
5382
5383         mine_transaction(&nodes[1], &closing_tx);
5384         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5385         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5386
5387         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5388         assert_eq!(spend_txn.len(), 1);
5389         check_spends!(spend_txn[0], closing_tx);
5390 }
5391
5392 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5393         let chanmon_cfgs = create_chanmon_cfgs(2);
5394         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5395         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5396         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5397         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5398
5399         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5400
5401         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5402         // present in B's local commitment transaction, but none of A's commitment transactions.
5403         nodes[1].node.claim_funds(payment_preimage);
5404         check_added_monitors!(nodes[1], 1);
5405         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5406
5407         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5408         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5409         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5410
5411         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5412         check_added_monitors!(nodes[0], 1);
5413         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5414         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5415         check_added_monitors!(nodes[1], 1);
5416
5417         let starting_block = nodes[1].best_block_info();
5418         let mut block = Block {
5419                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5420                 txdata: vec![],
5421         };
5422         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5423                 connect_block(&nodes[1], &block);
5424                 block.header.prev_blockhash = block.block_hash();
5425         }
5426         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5427         check_closed_broadcast!(nodes[1], true);
5428         check_added_monitors!(nodes[1], 1);
5429         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5430 }
5431
5432 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5433         let chanmon_cfgs = create_chanmon_cfgs(2);
5434         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5435         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5436         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5437         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5438
5439         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5440         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
5441         check_added_monitors!(nodes[0], 1);
5442
5443         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5444
5445         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5446         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5447         // to "time out" the HTLC.
5448
5449         let starting_block = nodes[1].best_block_info();
5450         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5451
5452         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5453                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5454                 header.prev_blockhash = header.block_hash();
5455         }
5456         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5457         check_closed_broadcast!(nodes[0], true);
5458         check_added_monitors!(nodes[0], 1);
5459         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5460 }
5461
5462 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5463         let chanmon_cfgs = create_chanmon_cfgs(3);
5464         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5465         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5466         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5467         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5468
5469         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5470         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5471         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5472         // actually revoked.
5473         let htlc_value = if use_dust { 50000 } else { 3000000 };
5474         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5475         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5476         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5477         check_added_monitors!(nodes[1], 1);
5478
5479         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5480         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5481         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5482         check_added_monitors!(nodes[0], 1);
5483         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5484         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5485         check_added_monitors!(nodes[1], 1);
5486         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5487         check_added_monitors!(nodes[1], 1);
5488         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5489
5490         if check_revoke_no_close {
5491                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5492                 check_added_monitors!(nodes[0], 1);
5493         }
5494
5495         let starting_block = nodes[1].best_block_info();
5496         let mut block = Block {
5497                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5498                 txdata: vec![],
5499         };
5500         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5501                 connect_block(&nodes[0], &block);
5502                 block.header.prev_blockhash = block.block_hash();
5503         }
5504         if !check_revoke_no_close {
5505                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5506                 check_closed_broadcast!(nodes[0], true);
5507                 check_added_monitors!(nodes[0], 1);
5508                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5509         } else {
5510                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5511         }
5512 }
5513
5514 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5515 // There are only a few cases to test here:
5516 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5517 //    broadcastable commitment transactions result in channel closure,
5518 //  * its included in an unrevoked-but-previous remote commitment transaction,
5519 //  * its included in the latest remote or local commitment transactions.
5520 // We test each of the three possible commitment transactions individually and use both dust and
5521 // non-dust HTLCs.
5522 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5523 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5524 // tested for at least one of the cases in other tests.
5525 #[test]
5526 fn htlc_claim_single_commitment_only_a() {
5527         do_htlc_claim_local_commitment_only(true);
5528         do_htlc_claim_local_commitment_only(false);
5529
5530         do_htlc_claim_current_remote_commitment_only(true);
5531         do_htlc_claim_current_remote_commitment_only(false);
5532 }
5533
5534 #[test]
5535 fn htlc_claim_single_commitment_only_b() {
5536         do_htlc_claim_previous_remote_commitment_only(true, false);
5537         do_htlc_claim_previous_remote_commitment_only(false, false);
5538         do_htlc_claim_previous_remote_commitment_only(true, true);
5539         do_htlc_claim_previous_remote_commitment_only(false, true);
5540 }
5541
5542 #[test]
5543 #[should_panic]
5544 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5545         let chanmon_cfgs = create_chanmon_cfgs(2);
5546         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5547         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5548         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5549         // Force duplicate randomness for every get-random call
5550         for node in nodes.iter() {
5551                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5552         }
5553
5554         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5555         let channel_value_satoshis=10000;
5556         let push_msat=10001;
5557         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5558         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5559         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5560         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5561
5562         // Create a second channel with the same random values. This used to panic due to a colliding
5563         // channel_id, but now panics due to a colliding outbound SCID alias.
5564         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5565 }
5566
5567 #[test]
5568 fn bolt2_open_channel_sending_node_checks_part2() {
5569         let chanmon_cfgs = create_chanmon_cfgs(2);
5570         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5571         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5572         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5573
5574         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5575         let channel_value_satoshis=2^24;
5576         let push_msat=10001;
5577         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5578
5579         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5580         let channel_value_satoshis=10000;
5581         // Test when push_msat is equal to 1000 * funding_satoshis.
5582         let push_msat=1000*channel_value_satoshis+1;
5583         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5584
5585         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5586         let channel_value_satoshis=10000;
5587         let push_msat=10001;
5588         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
5589         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5590         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5591
5592         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5593         // 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
5594         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5595
5596         // 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.
5597         assert!(BREAKDOWN_TIMEOUT>0);
5598         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5599
5600         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5601         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5602         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5603
5604         // 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.
5605         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5606         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5607         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5608         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5609         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5610 }
5611
5612 #[test]
5613 fn bolt2_open_channel_sane_dust_limit() {
5614         let chanmon_cfgs = create_chanmon_cfgs(2);
5615         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5616         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5617         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5618
5619         let channel_value_satoshis=1000000;
5620         let push_msat=10001;
5621         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5622         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5623         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5624         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5625
5626         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5627         let events = nodes[1].node.get_and_clear_pending_msg_events();
5628         let err_msg = match events[0] {
5629                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5630                         msg.clone()
5631                 },
5632                 _ => panic!("Unexpected event"),
5633         };
5634         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5635 }
5636
5637 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5638 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5639 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5640 // is no longer affordable once it's freed.
5641 #[test]
5642 fn test_fail_holding_cell_htlc_upon_free() {
5643         let chanmon_cfgs = create_chanmon_cfgs(2);
5644         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5645         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5646         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5647         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5648
5649         // First nodes[0] generates an update_fee, setting the channel's
5650         // pending_update_fee.
5651         {
5652                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5653                 *feerate_lock += 20;
5654         }
5655         nodes[0].node.timer_tick_occurred();
5656         check_added_monitors!(nodes[0], 1);
5657
5658         let events = nodes[0].node.get_and_clear_pending_msg_events();
5659         assert_eq!(events.len(), 1);
5660         let (update_msg, commitment_signed) = match events[0] {
5661                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5662                         (update_fee.as_ref(), commitment_signed)
5663                 },
5664                 _ => panic!("Unexpected event"),
5665         };
5666
5667         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5668
5669         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5670         let channel_reserve = chan_stat.channel_reserve_msat;
5671         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5672         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5673
5674         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5675         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5676         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5677
5678         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5679         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5680         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5681         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5682
5683         // Flush the pending fee update.
5684         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5685         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5686         check_added_monitors!(nodes[1], 1);
5687         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5688         check_added_monitors!(nodes[0], 1);
5689
5690         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5691         // HTLC, but now that the fee has been raised the payment will now fail, causing
5692         // us to surface its failure to the user.
5693         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5694         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5695         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);
5696         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 {}",
5697                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5698         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5699
5700         // Check that the payment failed to be sent out.
5701         let events = nodes[0].node.get_and_clear_pending_events();
5702         assert_eq!(events.len(), 2);
5703         match &events[0] {
5704                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5705                         assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5706                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5707                         assert_eq!(*payment_failed_permanently, false);
5708                         assert_eq!(*short_channel_id, Some(route.paths[0][0].short_channel_id));
5709                 },
5710                 _ => panic!("Unexpected event"),
5711         }
5712         match &events[1] {
5713                 &Event::PaymentFailed { ref payment_hash, .. } => {
5714                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5715                 },
5716                 _ => panic!("Unexpected event"),
5717         }
5718 }
5719
5720 // Test that if multiple HTLCs are released from the holding cell and one is
5721 // valid but the other is no longer valid upon release, the valid HTLC can be
5722 // successfully completed while the other one fails as expected.
5723 #[test]
5724 fn test_free_and_fail_holding_cell_htlcs() {
5725         let chanmon_cfgs = create_chanmon_cfgs(2);
5726         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5727         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5728         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5729         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5730
5731         // First nodes[0] generates an update_fee, setting the channel's
5732         // pending_update_fee.
5733         {
5734                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5735                 *feerate_lock += 200;
5736         }
5737         nodes[0].node.timer_tick_occurred();
5738         check_added_monitors!(nodes[0], 1);
5739
5740         let events = nodes[0].node.get_and_clear_pending_msg_events();
5741         assert_eq!(events.len(), 1);
5742         let (update_msg, commitment_signed) = match events[0] {
5743                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5744                         (update_fee.as_ref(), commitment_signed)
5745                 },
5746                 _ => panic!("Unexpected event"),
5747         };
5748
5749         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5750
5751         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5752         let channel_reserve = chan_stat.channel_reserve_msat;
5753         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5754         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5755
5756         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5757         let amt_1 = 20000;
5758         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
5759         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5760         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5761
5762         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5763         nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5764         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5765         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5766         let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5767         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2), payment_id_2).unwrap();
5768         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5769         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5770
5771         // Flush the pending fee update.
5772         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5773         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5774         check_added_monitors!(nodes[1], 1);
5775         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5776         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5777         check_added_monitors!(nodes[0], 2);
5778
5779         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5780         // but now that the fee has been raised the second payment will now fail, causing us
5781         // to surface its failure to the user. The first payment should succeed.
5782         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5783         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5784         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);
5785         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 {}",
5786                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5787         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5788
5789         // Check that the second payment failed to be sent out.
5790         let events = nodes[0].node.get_and_clear_pending_events();
5791         assert_eq!(events.len(), 2);
5792         match &events[0] {
5793                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5794                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5795                         assert_eq!(payment_hash_2.clone(), *payment_hash);
5796                         assert_eq!(*payment_failed_permanently, false);
5797                         assert_eq!(*short_channel_id, Some(route_2.paths[0][0].short_channel_id));
5798                 },
5799                 _ => panic!("Unexpected event"),
5800         }
5801         match &events[1] {
5802                 &Event::PaymentFailed { ref payment_hash, .. } => {
5803                         assert_eq!(payment_hash_2.clone(), *payment_hash);
5804                 },
5805                 _ => panic!("Unexpected event"),
5806         }
5807
5808         // Complete the first payment and the RAA from the fee update.
5809         let (payment_event, send_raa_event) = {
5810                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5811                 assert_eq!(msgs.len(), 2);
5812                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5813         };
5814         let raa = match send_raa_event {
5815                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5816                 _ => panic!("Unexpected event"),
5817         };
5818         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5819         check_added_monitors!(nodes[1], 1);
5820         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5821         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5822         let events = nodes[1].node.get_and_clear_pending_events();
5823         assert_eq!(events.len(), 1);
5824         match events[0] {
5825                 Event::PendingHTLCsForwardable { .. } => {},
5826                 _ => panic!("Unexpected event"),
5827         }
5828         nodes[1].node.process_pending_htlc_forwards();
5829         let events = nodes[1].node.get_and_clear_pending_events();
5830         assert_eq!(events.len(), 1);
5831         match events[0] {
5832                 Event::PaymentClaimable { .. } => {},
5833                 _ => panic!("Unexpected event"),
5834         }
5835         nodes[1].node.claim_funds(payment_preimage_1);
5836         check_added_monitors!(nodes[1], 1);
5837         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5838
5839         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5840         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5841         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5842         expect_payment_sent!(nodes[0], payment_preimage_1);
5843 }
5844
5845 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
5846 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
5847 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
5848 // once it's freed.
5849 #[test]
5850 fn test_fail_holding_cell_htlc_upon_free_multihop() {
5851         let chanmon_cfgs = create_chanmon_cfgs(3);
5852         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5853         // When this test was written, the default base fee floated based on the HTLC count.
5854         // It is now fixed, so we simply set the fee to the expected value here.
5855         let mut config = test_default_channel_config();
5856         config.channel_config.forwarding_fee_base_msat = 196;
5857         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5858         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5859         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5860         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
5861
5862         // First nodes[1] generates an update_fee, setting the channel's
5863         // pending_update_fee.
5864         {
5865                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
5866                 *feerate_lock += 20;
5867         }
5868         nodes[1].node.timer_tick_occurred();
5869         check_added_monitors!(nodes[1], 1);
5870
5871         let events = nodes[1].node.get_and_clear_pending_msg_events();
5872         assert_eq!(events.len(), 1);
5873         let (update_msg, commitment_signed) = match events[0] {
5874                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5875                         (update_fee.as_ref(), commitment_signed)
5876                 },
5877                 _ => panic!("Unexpected event"),
5878         };
5879
5880         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
5881
5882         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
5883         let channel_reserve = chan_stat.channel_reserve_msat;
5884         let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
5885         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_0_1.2);
5886
5887         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5888         let feemsat = 239;
5889         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
5890         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
5891         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
5892         let payment_event = {
5893                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5894                 check_added_monitors!(nodes[0], 1);
5895
5896                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5897                 assert_eq!(events.len(), 1);
5898
5899                 SendEvent::from_event(events.remove(0))
5900         };
5901         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5902         check_added_monitors!(nodes[1], 0);
5903         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5904         expect_pending_htlcs_forwardable!(nodes[1]);
5905
5906         chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
5907         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5908
5909         // Flush the pending fee update.
5910         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
5911         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5912         check_added_monitors!(nodes[2], 1);
5913         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
5914         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
5915         check_added_monitors!(nodes[1], 2);
5916
5917         // A final RAA message is generated to finalize the fee update.
5918         let events = nodes[1].node.get_and_clear_pending_msg_events();
5919         assert_eq!(events.len(), 1);
5920
5921         let raa_msg = match &events[0] {
5922                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
5923                         msg.clone()
5924                 },
5925                 _ => panic!("Unexpected event"),
5926         };
5927
5928         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
5929         check_added_monitors!(nodes[2], 1);
5930         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
5931
5932         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
5933         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
5934         assert_eq!(process_htlc_forwards_event.len(), 2);
5935         match &process_htlc_forwards_event[0] {
5936                 &Event::PendingHTLCsForwardable { .. } => {},
5937                 _ => panic!("Unexpected event"),
5938         }
5939
5940         // In response, we call ChannelManager's process_pending_htlc_forwards
5941         nodes[1].node.process_pending_htlc_forwards();
5942         check_added_monitors!(nodes[1], 1);
5943
5944         // This causes the HTLC to be failed backwards.
5945         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
5946         assert_eq!(fail_event.len(), 1);
5947         let (fail_msg, commitment_signed) = match &fail_event[0] {
5948                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
5949                         assert_eq!(updates.update_add_htlcs.len(), 0);
5950                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
5951                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
5952                         assert_eq!(updates.update_fail_htlcs.len(), 1);
5953                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
5954                 },
5955                 _ => panic!("Unexpected event"),
5956         };
5957
5958         // Pass the failure messages back to nodes[0].
5959         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5960         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5961
5962         // Complete the HTLC failure+removal process.
5963         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5964         check_added_monitors!(nodes[0], 1);
5965         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5966         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
5967         check_added_monitors!(nodes[1], 2);
5968         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
5969         assert_eq!(final_raa_event.len(), 1);
5970         let raa = match &final_raa_event[0] {
5971                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
5972                 _ => panic!("Unexpected event"),
5973         };
5974         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
5975         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
5976         check_added_monitors!(nodes[0], 1);
5977 }
5978
5979 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
5980 // 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.
5981 //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.
5982
5983 #[test]
5984 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
5985         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
5986         let chanmon_cfgs = create_chanmon_cfgs(2);
5987         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5988         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5989         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5990         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5991
5992         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
5993         route.paths[0][0].fee_msat = 100;
5994
5995         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
5996                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
5997         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5998         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send less than their minimum HTLC value", 1);
5999 }
6000
6001 #[test]
6002 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6003         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6004         let chanmon_cfgs = create_chanmon_cfgs(2);
6005         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6006         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6007         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6008         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6009
6010         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6011         route.paths[0][0].fee_msat = 0;
6012         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
6013                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6014
6015         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6016         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6017 }
6018
6019 #[test]
6020 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6021         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
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 (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6029         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6030         check_added_monitors!(nodes[0], 1);
6031         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6032         updates.update_add_htlcs[0].amount_msat = 0;
6033
6034         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6035         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6036         check_closed_broadcast!(nodes[1], true).unwrap();
6037         check_added_monitors!(nodes[1], 1);
6038         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6039 }
6040
6041 #[test]
6042 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6043         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6044         //It is enforced when constructing a route.
6045         let chanmon_cfgs = create_chanmon_cfgs(2);
6046         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6047         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6048         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6049         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6050
6051         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6052                 .with_features(nodes[1].node.invoice_features());
6053         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6054         route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6055         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::InvalidRoute { ref err },
6056                 assert_eq!(err, &"Channel CLTV overflowed?"));
6057 }
6058
6059 #[test]
6060 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6061         //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.
6062         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6063         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6064         let chanmon_cfgs = create_chanmon_cfgs(2);
6065         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6066         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6067         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6068         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6069         let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6070                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6071
6072         for i in 0..max_accepted_htlcs {
6073                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6074                 let payment_event = {
6075                         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6076                         check_added_monitors!(nodes[0], 1);
6077
6078                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6079                         assert_eq!(events.len(), 1);
6080                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6081                                 assert_eq!(htlcs[0].htlc_id, i);
6082                         } else {
6083                                 assert!(false);
6084                         }
6085                         SendEvent::from_event(events.remove(0))
6086                 };
6087                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6088                 check_added_monitors!(nodes[1], 0);
6089                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6090
6091                 expect_pending_htlcs_forwardable!(nodes[1]);
6092                 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6093         }
6094         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6095         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
6096                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6097
6098         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6099         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
6100 }
6101
6102 #[test]
6103 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6104         //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.
6105         let chanmon_cfgs = create_chanmon_cfgs(2);
6106         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6107         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6108         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6109         let channel_value = 100000;
6110         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6111         let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6112
6113         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6114
6115         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6116         // Manually create a route over our max in flight (which our router normally automatically
6117         // limits us to.
6118         route.paths[0][0].fee_msat =  max_in_flight + 1;
6119         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
6120                 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)));
6121
6122         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6123         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);
6124
6125         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6126 }
6127
6128 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6129 #[test]
6130 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6131         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6132         let chanmon_cfgs = create_chanmon_cfgs(2);
6133         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6134         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6135         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6136         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6137         let htlc_minimum_msat: u64;
6138         {
6139                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6140                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6141                 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6142                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6143         }
6144
6145         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6146         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6147         check_added_monitors!(nodes[0], 1);
6148         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6149         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6150         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6151         assert!(nodes[1].node.list_channels().is_empty());
6152         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6153         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()));
6154         check_added_monitors!(nodes[1], 1);
6155         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6156 }
6157
6158 #[test]
6159 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6160         //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
6161         let chanmon_cfgs = create_chanmon_cfgs(2);
6162         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6163         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6164         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6165         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6166
6167         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6168         let channel_reserve = chan_stat.channel_reserve_msat;
6169         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6170         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
6171         // The 2* and +1 are for the fee spike reserve.
6172         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6173
6174         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6175         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6176         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6177         check_added_monitors!(nodes[0], 1);
6178         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6179
6180         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6181         // at this time channel-initiatee receivers are not required to enforce that senders
6182         // respect the fee_spike_reserve.
6183         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6184         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6185
6186         assert!(nodes[1].node.list_channels().is_empty());
6187         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6188         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6189         check_added_monitors!(nodes[1], 1);
6190         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6191 }
6192
6193 #[test]
6194 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6195         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6196         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6197         let chanmon_cfgs = create_chanmon_cfgs(2);
6198         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6199         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6200         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6201         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6202
6203         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6204         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6205         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6206         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6207         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6208         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6209
6210         let mut msg = msgs::UpdateAddHTLC {
6211                 channel_id: chan.2,
6212                 htlc_id: 0,
6213                 amount_msat: 1000,
6214                 payment_hash: our_payment_hash,
6215                 cltv_expiry: htlc_cltv,
6216                 onion_routing_packet: onion_packet.clone(),
6217         };
6218
6219         for i in 0..super::channel::OUR_MAX_HTLCS {
6220                 msg.htlc_id = i as u64;
6221                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6222         }
6223         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6224         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6225
6226         assert!(nodes[1].node.list_channels().is_empty());
6227         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6228         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6229         check_added_monitors!(nodes[1], 1);
6230         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6231 }
6232
6233 #[test]
6234 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6235         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6236         let chanmon_cfgs = create_chanmon_cfgs(2);
6237         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6238         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6239         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6240         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6241
6242         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6243         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6244         check_added_monitors!(nodes[0], 1);
6245         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6246         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;
6247         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6248
6249         assert!(nodes[1].node.list_channels().is_empty());
6250         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6251         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6252         check_added_monitors!(nodes[1], 1);
6253         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6254 }
6255
6256 #[test]
6257 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6258         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6259         let chanmon_cfgs = create_chanmon_cfgs(2);
6260         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6261         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6262         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6263
6264         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6265         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6266         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6267         check_added_monitors!(nodes[0], 1);
6268         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6269         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6270         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6271
6272         assert!(nodes[1].node.list_channels().is_empty());
6273         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6274         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6275         check_added_monitors!(nodes[1], 1);
6276         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6277 }
6278
6279 #[test]
6280 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6281         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6282         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6283         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6284         let chanmon_cfgs = create_chanmon_cfgs(2);
6285         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6286         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6287         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6288
6289         create_announced_chan_between_nodes(&nodes, 0, 1);
6290         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6291         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6292         check_added_monitors!(nodes[0], 1);
6293         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6294         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6295
6296         //Disconnect and Reconnect
6297         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6298         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6299         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();
6300         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6301         assert_eq!(reestablish_1.len(), 1);
6302         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();
6303         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6304         assert_eq!(reestablish_2.len(), 1);
6305         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6306         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6307         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6308         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6309
6310         //Resend HTLC
6311         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6312         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6313         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6314         check_added_monitors!(nodes[1], 1);
6315         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6316
6317         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6318
6319         assert!(nodes[1].node.list_channels().is_empty());
6320         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6321         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6322         check_added_monitors!(nodes[1], 1);
6323         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6324 }
6325
6326 #[test]
6327 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6328         //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.
6329
6330         let chanmon_cfgs = create_chanmon_cfgs(2);
6331         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6332         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6333         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6334         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6335         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6336         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6337
6338         check_added_monitors!(nodes[0], 1);
6339         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6340         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6341
6342         let update_msg = msgs::UpdateFulfillHTLC{
6343                 channel_id: chan.2,
6344                 htlc_id: 0,
6345                 payment_preimage: our_payment_preimage,
6346         };
6347
6348         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6349
6350         assert!(nodes[0].node.list_channels().is_empty());
6351         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6352         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()));
6353         check_added_monitors!(nodes[0], 1);
6354         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6355 }
6356
6357 #[test]
6358 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6359         //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.
6360
6361         let chanmon_cfgs = create_chanmon_cfgs(2);
6362         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6363         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6364         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6365         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6366
6367         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6368         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6369         check_added_monitors!(nodes[0], 1);
6370         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6371         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6372
6373         let update_msg = msgs::UpdateFailHTLC{
6374                 channel_id: chan.2,
6375                 htlc_id: 0,
6376                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6377         };
6378
6379         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6380
6381         assert!(nodes[0].node.list_channels().is_empty());
6382         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6383         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()));
6384         check_added_monitors!(nodes[0], 1);
6385         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6386 }
6387
6388 #[test]
6389 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6390         //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.
6391
6392         let chanmon_cfgs = create_chanmon_cfgs(2);
6393         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6394         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6395         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6396         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6397
6398         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6399         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6400         check_added_monitors!(nodes[0], 1);
6401         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6402         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6403         let update_msg = msgs::UpdateFailMalformedHTLC{
6404                 channel_id: chan.2,
6405                 htlc_id: 0,
6406                 sha256_of_onion: [1; 32],
6407                 failure_code: 0x8000,
6408         };
6409
6410         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6411
6412         assert!(nodes[0].node.list_channels().is_empty());
6413         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6414         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()));
6415         check_added_monitors!(nodes[0], 1);
6416         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6417 }
6418
6419 #[test]
6420 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6421         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6422
6423         let chanmon_cfgs = create_chanmon_cfgs(2);
6424         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6425         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6426         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6427         create_announced_chan_between_nodes(&nodes, 0, 1);
6428
6429         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6430
6431         nodes[1].node.claim_funds(our_payment_preimage);
6432         check_added_monitors!(nodes[1], 1);
6433         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6434
6435         let events = nodes[1].node.get_and_clear_pending_msg_events();
6436         assert_eq!(events.len(), 1);
6437         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6438                 match events[0] {
6439                         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, .. } } => {
6440                                 assert!(update_add_htlcs.is_empty());
6441                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6442                                 assert!(update_fail_htlcs.is_empty());
6443                                 assert!(update_fail_malformed_htlcs.is_empty());
6444                                 assert!(update_fee.is_none());
6445                                 update_fulfill_htlcs[0].clone()
6446                         },
6447                         _ => panic!("Unexpected event"),
6448                 }
6449         };
6450
6451         update_fulfill_msg.htlc_id = 1;
6452
6453         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6454
6455         assert!(nodes[0].node.list_channels().is_empty());
6456         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6457         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6458         check_added_monitors!(nodes[0], 1);
6459         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6460 }
6461
6462 #[test]
6463 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6464         //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.
6465
6466         let chanmon_cfgs = create_chanmon_cfgs(2);
6467         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6468         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6469         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6470         create_announced_chan_between_nodes(&nodes, 0, 1);
6471
6472         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6473
6474         nodes[1].node.claim_funds(our_payment_preimage);
6475         check_added_monitors!(nodes[1], 1);
6476         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6477
6478         let events = nodes[1].node.get_and_clear_pending_msg_events();
6479         assert_eq!(events.len(), 1);
6480         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6481                 match events[0] {
6482                         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, .. } } => {
6483                                 assert!(update_add_htlcs.is_empty());
6484                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6485                                 assert!(update_fail_htlcs.is_empty());
6486                                 assert!(update_fail_malformed_htlcs.is_empty());
6487                                 assert!(update_fee.is_none());
6488                                 update_fulfill_htlcs[0].clone()
6489                         },
6490                         _ => panic!("Unexpected event"),
6491                 }
6492         };
6493
6494         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6495
6496         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6497
6498         assert!(nodes[0].node.list_channels().is_empty());
6499         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6500         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6501         check_added_monitors!(nodes[0], 1);
6502         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6503 }
6504
6505 #[test]
6506 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6507         //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.
6508
6509         let chanmon_cfgs = create_chanmon_cfgs(2);
6510         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6511         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6512         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6513         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6514
6515         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6516         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6517         check_added_monitors!(nodes[0], 1);
6518
6519         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6520         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6521
6522         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6523         check_added_monitors!(nodes[1], 0);
6524         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6525
6526         let events = nodes[1].node.get_and_clear_pending_msg_events();
6527
6528         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6529                 match events[0] {
6530                         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, .. } } => {
6531                                 assert!(update_add_htlcs.is_empty());
6532                                 assert!(update_fulfill_htlcs.is_empty());
6533                                 assert!(update_fail_htlcs.is_empty());
6534                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6535                                 assert!(update_fee.is_none());
6536                                 update_fail_malformed_htlcs[0].clone()
6537                         },
6538                         _ => panic!("Unexpected event"),
6539                 }
6540         };
6541         update_msg.failure_code &= !0x8000;
6542         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6543
6544         assert!(nodes[0].node.list_channels().is_empty());
6545         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6546         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6547         check_added_monitors!(nodes[0], 1);
6548         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6549 }
6550
6551 #[test]
6552 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6553         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6554         //    * 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.
6555
6556         let chanmon_cfgs = create_chanmon_cfgs(3);
6557         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6558         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6559         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6560         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6561         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6562
6563         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6564
6565         //First hop
6566         let mut payment_event = {
6567                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6568                 check_added_monitors!(nodes[0], 1);
6569                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6570                 assert_eq!(events.len(), 1);
6571                 SendEvent::from_event(events.remove(0))
6572         };
6573         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6574         check_added_monitors!(nodes[1], 0);
6575         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6576         expect_pending_htlcs_forwardable!(nodes[1]);
6577         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6578         assert_eq!(events_2.len(), 1);
6579         check_added_monitors!(nodes[1], 1);
6580         payment_event = SendEvent::from_event(events_2.remove(0));
6581         assert_eq!(payment_event.msgs.len(), 1);
6582
6583         //Second Hop
6584         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6585         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6586         check_added_monitors!(nodes[2], 0);
6587         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6588
6589         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6590         assert_eq!(events_3.len(), 1);
6591         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6592                 match events_3[0] {
6593                         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 } } => {
6594                                 assert!(update_add_htlcs.is_empty());
6595                                 assert!(update_fulfill_htlcs.is_empty());
6596                                 assert!(update_fail_htlcs.is_empty());
6597                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6598                                 assert!(update_fee.is_none());
6599                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6600                         },
6601                         _ => panic!("Unexpected event"),
6602                 }
6603         };
6604
6605         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6606
6607         check_added_monitors!(nodes[1], 0);
6608         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6609         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 }]);
6610         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6611         assert_eq!(events_4.len(), 1);
6612
6613         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6614         match events_4[0] {
6615                 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, .. } } => {
6616                         assert!(update_add_htlcs.is_empty());
6617                         assert!(update_fulfill_htlcs.is_empty());
6618                         assert_eq!(update_fail_htlcs.len(), 1);
6619                         assert!(update_fail_malformed_htlcs.is_empty());
6620                         assert!(update_fee.is_none());
6621                 },
6622                 _ => panic!("Unexpected event"),
6623         };
6624
6625         check_added_monitors!(nodes[1], 1);
6626 }
6627
6628 #[test]
6629 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6630         let chanmon_cfgs = create_chanmon_cfgs(3);
6631         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6632         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6633         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6634         create_announced_chan_between_nodes(&nodes, 0, 1);
6635         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6636
6637         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6638
6639         // First hop
6640         let mut payment_event = {
6641                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6642                 check_added_monitors!(nodes[0], 1);
6643                 SendEvent::from_node(&nodes[0])
6644         };
6645
6646         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6647         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6648         expect_pending_htlcs_forwardable!(nodes[1]);
6649         check_added_monitors!(nodes[1], 1);
6650         payment_event = SendEvent::from_node(&nodes[1]);
6651         assert_eq!(payment_event.msgs.len(), 1);
6652
6653         // Second Hop
6654         payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6655         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6656         check_added_monitors!(nodes[2], 0);
6657         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6658
6659         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6660         assert_eq!(events_3.len(), 1);
6661         match events_3[0] {
6662                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6663                         let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6664                         // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6665                         update_msg.failure_code |= 0x2000;
6666
6667                         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6668                         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6669                 },
6670                 _ => panic!("Unexpected event"),
6671         }
6672
6673         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6674                 vec![HTLCDestination::NextHopChannel {
6675                         node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6676         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6677         assert_eq!(events_4.len(), 1);
6678         check_added_monitors!(nodes[1], 1);
6679
6680         match events_4[0] {
6681                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6682                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6683                         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6684                 },
6685                 _ => panic!("Unexpected event"),
6686         }
6687
6688         let events_5 = nodes[0].node.get_and_clear_pending_events();
6689         assert_eq!(events_5.len(), 2);
6690
6691         // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6692         // the node originating the error to its next hop.
6693         match events_5[0] {
6694                 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6695                 } => {
6696                         assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6697                         assert!(is_permanent);
6698                         assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6699                 },
6700                 _ => panic!("Unexpected event"),
6701         }
6702         match events_5[1] {
6703                 Event::PaymentFailed { payment_hash, .. } => {
6704                         assert_eq!(payment_hash, our_payment_hash);
6705                 },
6706                 _ => panic!("Unexpected event"),
6707         }
6708
6709         // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6710 }
6711
6712 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6713         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6714         // 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
6715         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6716
6717         let mut chanmon_cfgs = create_chanmon_cfgs(2);
6718         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6719         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6720         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6721         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6722         let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
6723
6724         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6725                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6726
6727         // We route 2 dust-HTLCs between A and B
6728         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6729         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6730         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6731
6732         // Cache one local commitment tx as previous
6733         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6734
6735         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6736         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6737         check_added_monitors!(nodes[1], 0);
6738         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6739         check_added_monitors!(nodes[1], 1);
6740
6741         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6742         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6743         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6744         check_added_monitors!(nodes[0], 1);
6745
6746         // Cache one local commitment tx as lastest
6747         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6748
6749         let events = nodes[0].node.get_and_clear_pending_msg_events();
6750         match events[0] {
6751                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6752                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6753                 },
6754                 _ => panic!("Unexpected event"),
6755         }
6756         match events[1] {
6757                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6758                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6759                 },
6760                 _ => panic!("Unexpected event"),
6761         }
6762
6763         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6764         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6765         if announce_latest {
6766                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6767         } else {
6768                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6769         }
6770
6771         check_closed_broadcast!(nodes[0], true);
6772         check_added_monitors!(nodes[0], 1);
6773         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6774
6775         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6776         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6777         let events = nodes[0].node.get_and_clear_pending_events();
6778         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6779         assert_eq!(events.len(), 4);
6780         let mut first_failed = false;
6781         for event in events {
6782                 match event {
6783                         Event::PaymentPathFailed { payment_hash, .. } => {
6784                                 if payment_hash == payment_hash_1 {
6785                                         assert!(!first_failed);
6786                                         first_failed = true;
6787                                 } else {
6788                                         assert_eq!(payment_hash, payment_hash_2);
6789                                 }
6790                         },
6791                         Event::PaymentFailed { .. } => {}
6792                         _ => panic!("Unexpected event"),
6793                 }
6794         }
6795 }
6796
6797 #[test]
6798 fn test_failure_delay_dust_htlc_local_commitment() {
6799         do_test_failure_delay_dust_htlc_local_commitment(true);
6800         do_test_failure_delay_dust_htlc_local_commitment(false);
6801 }
6802
6803 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6804         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6805         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6806         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6807         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6808         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6809         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6810
6811         let chanmon_cfgs = create_chanmon_cfgs(3);
6812         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6813         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6814         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6815         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6816
6817         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6818                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6819
6820         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6821         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6822
6823         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6824         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6825
6826         // We revoked bs_commitment_tx
6827         if revoked {
6828                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6829                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6830         }
6831
6832         let mut timeout_tx = Vec::new();
6833         if local {
6834                 // We fail dust-HTLC 1 by broadcast of local commitment tx
6835                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
6836                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6837                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6838                 expect_payment_failed!(nodes[0], dust_hash, false);
6839
6840                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
6841                 check_closed_broadcast!(nodes[0], true);
6842                 check_added_monitors!(nodes[0], 1);
6843                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6844                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6845                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6846                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6847                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6848                 mine_transaction(&nodes[0], &timeout_tx[0]);
6849                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6850                 expect_payment_failed!(nodes[0], non_dust_hash, false);
6851         } else {
6852                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6853                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
6854                 check_closed_broadcast!(nodes[0], true);
6855                 check_added_monitors!(nodes[0], 1);
6856                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6857                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6858
6859                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
6860                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
6861                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
6862                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
6863                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
6864                 // dust HTLC should have been failed.
6865                 expect_payment_failed!(nodes[0], dust_hash, false);
6866
6867                 if !revoked {
6868                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6869                 } else {
6870                         assert_eq!(timeout_tx[0].lock_time.0, 12);
6871                 }
6872                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
6873                 mine_transaction(&nodes[0], &timeout_tx[0]);
6874                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6875                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6876                 expect_payment_failed!(nodes[0], non_dust_hash, false);
6877         }
6878 }
6879
6880 #[test]
6881 fn test_sweep_outbound_htlc_failure_update() {
6882         do_test_sweep_outbound_htlc_failure_update(false, true);
6883         do_test_sweep_outbound_htlc_failure_update(false, false);
6884         do_test_sweep_outbound_htlc_failure_update(true, false);
6885 }
6886
6887 #[test]
6888 fn test_user_configurable_csv_delay() {
6889         // We test our channel constructors yield errors when we pass them absurd csv delay
6890
6891         let mut low_our_to_self_config = UserConfig::default();
6892         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
6893         let mut high_their_to_self_config = UserConfig::default();
6894         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
6895         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6896         let chanmon_cfgs = create_chanmon_cfgs(2);
6897         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6898         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6899         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6900
6901         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6902         if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6903                 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
6904                 &low_our_to_self_config, 0, 42)
6905         {
6906                 match error {
6907                         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())); },
6908                         _ => panic!("Unexpected event"),
6909                 }
6910         } else { assert!(false) }
6911
6912         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6913         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6914         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6915         open_channel.to_self_delay = 200;
6916         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6917                 &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,
6918                 &low_our_to_self_config, 0, &nodes[0].logger, 42)
6919         {
6920                 match error {
6921                         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()));  },
6922                         _ => panic!("Unexpected event"),
6923                 }
6924         } else { assert!(false); }
6925
6926         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6927         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6928         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()));
6929         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6930         accept_channel.to_self_delay = 200;
6931         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
6932         let reason_msg;
6933         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
6934                 match action {
6935                         &ErrorAction::SendErrorMessage { ref msg } => {
6936                                 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()));
6937                                 reason_msg = msg.data.clone();
6938                         },
6939                         _ => { panic!(); }
6940                 }
6941         } else { panic!(); }
6942         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
6943
6944         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
6945         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6946         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6947         open_channel.to_self_delay = 200;
6948         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6949                 &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,
6950                 &high_their_to_self_config, 0, &nodes[0].logger, 42)
6951         {
6952                 match error {
6953                         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())); },
6954                         _ => panic!("Unexpected event"),
6955                 }
6956         } else { assert!(false); }
6957 }
6958
6959 #[test]
6960 fn test_check_htlc_underpaying() {
6961         // Send payment through A -> B but A is maliciously
6962         // sending a probe payment (i.e less than expected value0
6963         // to B, B should refuse payment.
6964
6965         let chanmon_cfgs = create_chanmon_cfgs(2);
6966         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6967         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6968         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6969
6970         // Create some initial channels
6971         create_announced_chan_between_nodes(&nodes, 0, 1);
6972
6973         let scorer = test_utils::TestScorer::new();
6974         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
6975         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV).with_features(nodes[1].node.invoice_features());
6976         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None, 10_000, TEST_FINAL_CLTV, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
6977         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
6978         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
6979         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6980         check_added_monitors!(nodes[0], 1);
6981
6982         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6983         assert_eq!(events.len(), 1);
6984         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
6985         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6986         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6987
6988         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
6989         // and then will wait a second random delay before failing the HTLC back:
6990         expect_pending_htlcs_forwardable!(nodes[1]);
6991         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
6992
6993         // Node 3 is expecting payment of 100_000 but received 10_000,
6994         // it should fail htlc like we didn't know the preimage.
6995         nodes[1].node.process_pending_htlc_forwards();
6996
6997         let events = nodes[1].node.get_and_clear_pending_msg_events();
6998         assert_eq!(events.len(), 1);
6999         let (update_fail_htlc, commitment_signed) = match events[0] {
7000                 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 } } => {
7001                         assert!(update_add_htlcs.is_empty());
7002                         assert!(update_fulfill_htlcs.is_empty());
7003                         assert_eq!(update_fail_htlcs.len(), 1);
7004                         assert!(update_fail_malformed_htlcs.is_empty());
7005                         assert!(update_fee.is_none());
7006                         (update_fail_htlcs[0].clone(), commitment_signed)
7007                 },
7008                 _ => panic!("Unexpected event"),
7009         };
7010         check_added_monitors!(nodes[1], 1);
7011
7012         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7013         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7014
7015         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7016         let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7017         expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7018         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7019 }
7020
7021 #[test]
7022 fn test_announce_disable_channels() {
7023         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7024         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7025
7026         let chanmon_cfgs = create_chanmon_cfgs(2);
7027         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7028         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7029         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7030
7031         create_announced_chan_between_nodes(&nodes, 0, 1);
7032         create_announced_chan_between_nodes(&nodes, 1, 0);
7033         create_announced_chan_between_nodes(&nodes, 0, 1);
7034
7035         // Disconnect peers
7036         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7037         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7038
7039         nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7040         nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7041         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7042         assert_eq!(msg_events.len(), 3);
7043         let mut chans_disabled = HashMap::new();
7044         for e in msg_events {
7045                 match e {
7046                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7047                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7048                                 // Check that each channel gets updated exactly once
7049                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7050                                         panic!("Generated ChannelUpdate for wrong chan!");
7051                                 }
7052                         },
7053                         _ => panic!("Unexpected event"),
7054                 }
7055         }
7056         // Reconnect peers
7057         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();
7058         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7059         assert_eq!(reestablish_1.len(), 3);
7060         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();
7061         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7062         assert_eq!(reestablish_2.len(), 3);
7063
7064         // Reestablish chan_1
7065         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7066         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7067         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7068         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7069         // Reestablish chan_2
7070         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7071         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7072         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7073         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7074         // Reestablish chan_3
7075         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7076         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7077         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7078         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7079
7080         nodes[0].node.timer_tick_occurred();
7081         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7082         nodes[0].node.timer_tick_occurred();
7083         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7084         assert_eq!(msg_events.len(), 3);
7085         for e in msg_events {
7086                 match e {
7087                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7088                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7089                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7090                                         // Each update should have a higher timestamp than the previous one, replacing
7091                                         // the old one.
7092                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7093                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7094                                 }
7095                         },
7096                         _ => panic!("Unexpected event"),
7097                 }
7098         }
7099         // Check that each channel gets updated exactly once
7100         assert!(chans_disabled.is_empty());
7101 }
7102
7103 #[test]
7104 fn test_bump_penalty_txn_on_revoked_commitment() {
7105         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7106         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7107
7108         let chanmon_cfgs = create_chanmon_cfgs(2);
7109         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7110         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7111         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7112
7113         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7114
7115         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7116         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7117                 .with_features(nodes[0].node.invoice_features());
7118         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7119         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7120
7121         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7122         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7123         assert_eq!(revoked_txn[0].output.len(), 4);
7124         assert_eq!(revoked_txn[0].input.len(), 1);
7125         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7126         let revoked_txid = revoked_txn[0].txid();
7127
7128         let mut penalty_sum = 0;
7129         for outp in revoked_txn[0].output.iter() {
7130                 if outp.script_pubkey.is_v0_p2wsh() {
7131                         penalty_sum += outp.value;
7132                 }
7133         }
7134
7135         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7136         let header_114 = connect_blocks(&nodes[1], 14);
7137
7138         // Actually revoke tx by claiming a HTLC
7139         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7140         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7141         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7142         check_added_monitors!(nodes[1], 1);
7143
7144         // One or more justice tx should have been broadcast, check it
7145         let penalty_1;
7146         let feerate_1;
7147         {
7148                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7149                 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7150                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7151                 assert_eq!(node_txn[0].output.len(), 1);
7152                 check_spends!(node_txn[0], revoked_txn[0]);
7153                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7154                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7155                 penalty_1 = node_txn[0].txid();
7156                 node_txn.clear();
7157         };
7158
7159         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7160         connect_blocks(&nodes[1], 15);
7161         let mut penalty_2 = penalty_1;
7162         let mut feerate_2 = 0;
7163         {
7164                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7165                 assert_eq!(node_txn.len(), 1);
7166                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7167                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7168                         assert_eq!(node_txn[0].output.len(), 1);
7169                         check_spends!(node_txn[0], revoked_txn[0]);
7170                         penalty_2 = node_txn[0].txid();
7171                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7172                         assert_ne!(penalty_2, penalty_1);
7173                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7174                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7175                         // Verify 25% bump heuristic
7176                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7177                         node_txn.clear();
7178                 }
7179         }
7180         assert_ne!(feerate_2, 0);
7181
7182         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7183         connect_blocks(&nodes[1], 1);
7184         let penalty_3;
7185         let mut feerate_3 = 0;
7186         {
7187                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7188                 assert_eq!(node_txn.len(), 1);
7189                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7190                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7191                         assert_eq!(node_txn[0].output.len(), 1);
7192                         check_spends!(node_txn[0], revoked_txn[0]);
7193                         penalty_3 = node_txn[0].txid();
7194                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7195                         assert_ne!(penalty_3, penalty_2);
7196                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7197                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7198                         // Verify 25% bump heuristic
7199                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7200                         node_txn.clear();
7201                 }
7202         }
7203         assert_ne!(feerate_3, 0);
7204
7205         nodes[1].node.get_and_clear_pending_events();
7206         nodes[1].node.get_and_clear_pending_msg_events();
7207 }
7208
7209 #[test]
7210 fn test_bump_penalty_txn_on_revoked_htlcs() {
7211         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7212         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7213
7214         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7215         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7216         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7217         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7218         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7219
7220         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7221         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7222         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_features(nodes[1].node.invoice_features());
7223         let scorer = test_utils::TestScorer::new();
7224         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7225         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7226                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7227         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7228         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_features(nodes[0].node.invoice_features());
7229         let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7230                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7231         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7232
7233         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7234         assert_eq!(revoked_local_txn[0].input.len(), 1);
7235         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7236
7237         // Revoke local commitment tx
7238         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7239
7240         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7241         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7242         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7243         check_closed_broadcast!(nodes[1], true);
7244         check_added_monitors!(nodes[1], 1);
7245         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7246         connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7247
7248         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
7249         assert_eq!(revoked_htlc_txn.len(), 2);
7250
7251         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7252         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7253         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7254
7255         assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7256         assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7257         assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7258         check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7259
7260         // Broadcast set of revoked txn on A
7261         let hash_128 = connect_blocks(&nodes[0], 40);
7262         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7263         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7264         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7265         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] });
7266         let events = nodes[0].node.get_and_clear_pending_events();
7267         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7268         match events.last().unwrap() {
7269                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7270                 _ => panic!("Unexpected event"),
7271         }
7272         let first;
7273         let feerate_1;
7274         let penalty_txn;
7275         {
7276                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7277                 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7278                 // Verify claim tx are spending revoked HTLC txn
7279
7280                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7281                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7282                 // which are included in the same block (they are broadcasted because we scan the
7283                 // transactions linearly and generate claims as we go, they likely should be removed in the
7284                 // future).
7285                 assert_eq!(node_txn[0].input.len(), 1);
7286                 check_spends!(node_txn[0], revoked_local_txn[0]);
7287                 assert_eq!(node_txn[1].input.len(), 1);
7288                 check_spends!(node_txn[1], revoked_local_txn[0]);
7289                 assert_eq!(node_txn[2].input.len(), 1);
7290                 check_spends!(node_txn[2], revoked_local_txn[0]);
7291
7292                 // Each of the three justice transactions claim a separate (single) output of the three
7293                 // available, which we check here:
7294                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7295                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7296                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7297
7298                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7299                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7300
7301                 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7302                 // output, checked above).
7303                 assert_eq!(node_txn[3].input.len(), 2);
7304                 assert_eq!(node_txn[3].output.len(), 1);
7305                 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7306
7307                 first = node_txn[3].txid();
7308                 // Store both feerates for later comparison
7309                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7310                 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7311                 penalty_txn = vec![node_txn[2].clone()];
7312                 node_txn.clear();
7313         }
7314
7315         // Connect one more block to see if bumped penalty are issued for HTLC txn
7316         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7317         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7318         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7319         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7320
7321         // Few more blocks to confirm penalty txn
7322         connect_blocks(&nodes[0], 4);
7323         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7324         let header_144 = connect_blocks(&nodes[0], 9);
7325         let node_txn = {
7326                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7327                 assert_eq!(node_txn.len(), 1);
7328
7329                 assert_eq!(node_txn[0].input.len(), 2);
7330                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7331                 // Verify bumped tx is different and 25% bump heuristic
7332                 assert_ne!(first, node_txn[0].txid());
7333                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7334                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7335                 assert!(feerate_2 * 100 > feerate_1 * 125);
7336                 let txn = vec![node_txn[0].clone()];
7337                 node_txn.clear();
7338                 txn
7339         };
7340         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7341         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7342         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7343         connect_blocks(&nodes[0], 20);
7344         {
7345                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7346                 // We verify than no new transaction has been broadcast because previously
7347                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7348                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7349                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7350                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7351                 // up bumped justice generation.
7352                 assert_eq!(node_txn.len(), 0);
7353                 node_txn.clear();
7354         }
7355         check_closed_broadcast!(nodes[0], true);
7356         check_added_monitors!(nodes[0], 1);
7357 }
7358
7359 #[test]
7360 fn test_bump_penalty_txn_on_remote_commitment() {
7361         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7362         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7363
7364         // Create 2 HTLCs
7365         // Provide preimage for one
7366         // Check aggregation
7367
7368         let chanmon_cfgs = create_chanmon_cfgs(2);
7369         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7370         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7371         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7372
7373         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7374         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7375         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7376
7377         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7378         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7379         assert_eq!(remote_txn[0].output.len(), 4);
7380         assert_eq!(remote_txn[0].input.len(), 1);
7381         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7382
7383         // Claim a HTLC without revocation (provide B monitor with preimage)
7384         nodes[1].node.claim_funds(payment_preimage);
7385         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7386         mine_transaction(&nodes[1], &remote_txn[0]);
7387         check_added_monitors!(nodes[1], 2);
7388         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7389
7390         // One or more claim tx should have been broadcast, check it
7391         let timeout;
7392         let preimage;
7393         let preimage_bump;
7394         let feerate_timeout;
7395         let feerate_preimage;
7396         {
7397                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7398                 // 3 transactions including:
7399                 //   preimage and timeout sweeps from remote commitment + preimage sweep bump
7400                 assert_eq!(node_txn.len(), 3);
7401                 assert_eq!(node_txn[0].input.len(), 1);
7402                 assert_eq!(node_txn[1].input.len(), 1);
7403                 assert_eq!(node_txn[2].input.len(), 1);
7404                 check_spends!(node_txn[0], remote_txn[0]);
7405                 check_spends!(node_txn[1], remote_txn[0]);
7406                 check_spends!(node_txn[2], remote_txn[0]);
7407
7408                 preimage = node_txn[0].txid();
7409                 let index = node_txn[0].input[0].previous_output.vout;
7410                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7411                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7412
7413                 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7414                         (node_txn[2].clone(), node_txn[1].clone())
7415                 } else {
7416                         (node_txn[1].clone(), node_txn[2].clone())
7417                 };
7418
7419                 preimage_bump = preimage_bump_tx;
7420                 check_spends!(preimage_bump, remote_txn[0]);
7421                 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7422
7423                 timeout = timeout_tx.txid();
7424                 let index = timeout_tx.input[0].previous_output.vout;
7425                 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7426                 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7427
7428                 node_txn.clear();
7429         };
7430         assert_ne!(feerate_timeout, 0);
7431         assert_ne!(feerate_preimage, 0);
7432
7433         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7434         connect_blocks(&nodes[1], 15);
7435         {
7436                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7437                 assert_eq!(node_txn.len(), 1);
7438                 assert_eq!(node_txn[0].input.len(), 1);
7439                 assert_eq!(preimage_bump.input.len(), 1);
7440                 check_spends!(node_txn[0], remote_txn[0]);
7441                 check_spends!(preimage_bump, remote_txn[0]);
7442
7443                 let index = preimage_bump.input[0].previous_output.vout;
7444                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7445                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7446                 assert!(new_feerate * 100 > feerate_timeout * 125);
7447                 assert_ne!(timeout, preimage_bump.txid());
7448
7449                 let index = node_txn[0].input[0].previous_output.vout;
7450                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7451                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7452                 assert!(new_feerate * 100 > feerate_preimage * 125);
7453                 assert_ne!(preimage, node_txn[0].txid());
7454
7455                 node_txn.clear();
7456         }
7457
7458         nodes[1].node.get_and_clear_pending_events();
7459         nodes[1].node.get_and_clear_pending_msg_events();
7460 }
7461
7462 #[test]
7463 fn test_counterparty_raa_skip_no_crash() {
7464         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7465         // commitment transaction, we would have happily carried on and provided them the next
7466         // commitment transaction based on one RAA forward. This would probably eventually have led to
7467         // channel closure, but it would not have resulted in funds loss. Still, our
7468         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7469         // check simply that the channel is closed in response to such an RAA, but don't check whether
7470         // we decide to punish our counterparty for revoking their funds (as we don't currently
7471         // implement that).
7472         let chanmon_cfgs = create_chanmon_cfgs(2);
7473         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7474         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7475         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7476         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7477
7478         let per_commitment_secret;
7479         let next_per_commitment_point;
7480         {
7481                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7482                 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7483                 let keys = guard.channel_by_id.get_mut(&channel_id).unwrap().get_signer();
7484
7485                 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7486
7487                 // Make signer believe we got a counterparty signature, so that it allows the revocation
7488                 keys.get_enforcement_state().last_holder_commitment -= 1;
7489                 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7490
7491                 // Must revoke without gaps
7492                 keys.get_enforcement_state().last_holder_commitment -= 1;
7493                 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7494
7495                 keys.get_enforcement_state().last_holder_commitment -= 1;
7496                 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7497                         &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7498         }
7499
7500         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7501                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7502         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7503         check_added_monitors!(nodes[1], 1);
7504         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7505 }
7506
7507 #[test]
7508 fn test_bump_txn_sanitize_tracking_maps() {
7509         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7510         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7511
7512         let chanmon_cfgs = create_chanmon_cfgs(2);
7513         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7514         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7515         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7516
7517         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7518         // Lock HTLC in both directions
7519         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7520         let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7521
7522         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7523         assert_eq!(revoked_local_txn[0].input.len(), 1);
7524         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7525
7526         // Revoke local commitment tx
7527         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7528
7529         // Broadcast set of revoked txn on A
7530         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7531         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7532         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7533
7534         mine_transaction(&nodes[0], &revoked_local_txn[0]);
7535         check_closed_broadcast!(nodes[0], true);
7536         check_added_monitors!(nodes[0], 1);
7537         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7538         let penalty_txn = {
7539                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7540                 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7541                 check_spends!(node_txn[0], revoked_local_txn[0]);
7542                 check_spends!(node_txn[1], revoked_local_txn[0]);
7543                 check_spends!(node_txn[2], revoked_local_txn[0]);
7544                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7545                 node_txn.clear();
7546                 penalty_txn
7547         };
7548         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7549         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7550         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7551         {
7552                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7553                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7554                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7555         }
7556 }
7557
7558 #[test]
7559 fn test_pending_claimed_htlc_no_balance_underflow() {
7560         // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
7561         // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
7562         let chanmon_cfgs = create_chanmon_cfgs(2);
7563         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7564         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7565         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7566         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
7567
7568         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
7569         nodes[1].node.claim_funds(payment_preimage);
7570         expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
7571         check_added_monitors!(nodes[1], 1);
7572         let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7573
7574         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
7575         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
7576         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
7577         check_added_monitors!(nodes[0], 1);
7578         let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7579
7580         // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
7581         // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
7582         // can get our balance.
7583
7584         // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
7585         // the public key of the only hop. This works around ChannelDetails not showing the
7586         // almost-claimed HTLC as available balance.
7587         let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
7588         route.payment_params = None; // This is all wrong, but unnecessary
7589         route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
7590         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
7591         nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
7592
7593         assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
7594 }
7595
7596 #[test]
7597 fn test_channel_conf_timeout() {
7598         // Tests that, for inbound channels, we give up on them if the funding transaction does not
7599         // confirm within 2016 blocks, as recommended by BOLT 2.
7600         let chanmon_cfgs = create_chanmon_cfgs(2);
7601         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7602         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7603         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7604
7605         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7606
7607         // The outbound node should wait forever for confirmation:
7608         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7609         // copied here instead of directly referencing the constant.
7610         connect_blocks(&nodes[0], 2016);
7611         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7612
7613         // The inbound node should fail the channel after exactly 2016 blocks
7614         connect_blocks(&nodes[1], 2015);
7615         check_added_monitors!(nodes[1], 0);
7616         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7617
7618         connect_blocks(&nodes[1], 1);
7619         check_added_monitors!(nodes[1], 1);
7620         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
7621         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7622         assert_eq!(close_ev.len(), 1);
7623         match close_ev[0] {
7624                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7625                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7626                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7627                 },
7628                 _ => panic!("Unexpected event"),
7629         }
7630 }
7631
7632 #[test]
7633 fn test_override_channel_config() {
7634         let chanmon_cfgs = create_chanmon_cfgs(2);
7635         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7636         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7637         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7638
7639         // Node0 initiates a channel to node1 using the override config.
7640         let mut override_config = UserConfig::default();
7641         override_config.channel_handshake_config.our_to_self_delay = 200;
7642
7643         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7644
7645         // Assert the channel created by node0 is using the override config.
7646         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7647         assert_eq!(res.channel_flags, 0);
7648         assert_eq!(res.to_self_delay, 200);
7649 }
7650
7651 #[test]
7652 fn test_override_0msat_htlc_minimum() {
7653         let mut zero_config = UserConfig::default();
7654         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7655         let chanmon_cfgs = create_chanmon_cfgs(2);
7656         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7657         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7658         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7659
7660         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7661         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7662         assert_eq!(res.htlc_minimum_msat, 1);
7663
7664         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7665         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7666         assert_eq!(res.htlc_minimum_msat, 1);
7667 }
7668
7669 #[test]
7670 fn test_channel_update_has_correct_htlc_maximum_msat() {
7671         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7672         // Bolt 7 specifies that if present `htlc_maximum_msat`:
7673         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7674         // 90% of the `channel_value`.
7675         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7676
7677         let mut config_30_percent = UserConfig::default();
7678         config_30_percent.channel_handshake_config.announced_channel = true;
7679         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7680         let mut config_50_percent = UserConfig::default();
7681         config_50_percent.channel_handshake_config.announced_channel = true;
7682         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7683         let mut config_95_percent = UserConfig::default();
7684         config_95_percent.channel_handshake_config.announced_channel = true;
7685         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7686         let mut config_100_percent = UserConfig::default();
7687         config_100_percent.channel_handshake_config.announced_channel = true;
7688         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7689
7690         let chanmon_cfgs = create_chanmon_cfgs(4);
7691         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7692         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)]);
7693         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7694
7695         let channel_value_satoshis = 100000;
7696         let channel_value_msat = channel_value_satoshis * 1000;
7697         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7698         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7699         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7700
7701         let (node_0_chan_update, node_1_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7702         let (node_2_chan_update, node_3_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7703
7704         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7705         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7706         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7707         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7708         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7709         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7710
7711         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7712         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7713         // `channel_value`.
7714         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7715         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7716         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7717         // `channel_value`.
7718         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7719 }
7720
7721 #[test]
7722 fn test_manually_accept_inbound_channel_request() {
7723         let mut manually_accept_conf = UserConfig::default();
7724         manually_accept_conf.manually_accept_inbound_channels = true;
7725         let chanmon_cfgs = create_chanmon_cfgs(2);
7726         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7727         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7728         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7729
7730         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7731         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7732
7733         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7734
7735         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7736         // accepting the inbound channel request.
7737         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7738
7739         let events = nodes[1].node.get_and_clear_pending_events();
7740         match events[0] {
7741                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7742                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7743                 }
7744                 _ => panic!("Unexpected event"),
7745         }
7746
7747         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7748         assert_eq!(accept_msg_ev.len(), 1);
7749
7750         match accept_msg_ev[0] {
7751                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7752                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7753                 }
7754                 _ => panic!("Unexpected event"),
7755         }
7756
7757         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7758
7759         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7760         assert_eq!(close_msg_ev.len(), 1);
7761
7762         let events = nodes[1].node.get_and_clear_pending_events();
7763         match events[0] {
7764                 Event::ChannelClosed { user_channel_id, .. } => {
7765                         assert_eq!(user_channel_id, 23);
7766                 }
7767                 _ => panic!("Unexpected event"),
7768         }
7769 }
7770
7771 #[test]
7772 fn test_manually_reject_inbound_channel_request() {
7773         let mut manually_accept_conf = UserConfig::default();
7774         manually_accept_conf.manually_accept_inbound_channels = true;
7775         let chanmon_cfgs = create_chanmon_cfgs(2);
7776         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7777         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7778         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7779
7780         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7781         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7782
7783         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7784
7785         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7786         // rejecting the inbound channel request.
7787         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7788
7789         let events = nodes[1].node.get_and_clear_pending_events();
7790         match events[0] {
7791                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7792                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7793                 }
7794                 _ => panic!("Unexpected event"),
7795         }
7796
7797         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7798         assert_eq!(close_msg_ev.len(), 1);
7799
7800         match close_msg_ev[0] {
7801                 MessageSendEvent::HandleError { ref node_id, .. } => {
7802                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7803                 }
7804                 _ => panic!("Unexpected event"),
7805         }
7806         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
7807 }
7808
7809 #[test]
7810 fn test_reject_funding_before_inbound_channel_accepted() {
7811         // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
7812         // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
7813         // the node operator before the counterparty sends a `FundingCreated` message. If a
7814         // `FundingCreated` message is received before the channel is accepted, it should be rejected
7815         // and the channel should be closed.
7816         let mut manually_accept_conf = UserConfig::default();
7817         manually_accept_conf.manually_accept_inbound_channels = true;
7818         let chanmon_cfgs = create_chanmon_cfgs(2);
7819         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7820         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7821         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7822
7823         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7824         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7825         let temp_channel_id = res.temporary_channel_id;
7826
7827         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7828
7829         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
7830         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7831
7832         // Clear the `Event::OpenChannelRequest` event without responding to the request.
7833         nodes[1].node.get_and_clear_pending_events();
7834
7835         // Get the `AcceptChannel` message of `nodes[1]` without calling
7836         // `ChannelManager::accept_inbound_channel`, which generates a
7837         // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
7838         // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
7839         // succeed when `nodes[0]` is passed to it.
7840         let accept_chan_msg = {
7841                 let mut node_1_per_peer_lock;
7842                 let mut node_1_peer_state_lock;
7843                 let channel =  get_channel_ref!(&nodes[1], nodes[0], node_1_per_peer_lock, node_1_peer_state_lock, temp_channel_id);
7844                 channel.get_accept_channel_message()
7845         };
7846         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
7847
7848         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
7849
7850         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
7851         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
7852
7853         // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
7854         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
7855
7856         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7857         assert_eq!(close_msg_ev.len(), 1);
7858
7859         let expected_err = "FundingCreated message received before the channel was accepted";
7860         match close_msg_ev[0] {
7861                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
7862                         assert_eq!(msg.channel_id, temp_channel_id);
7863                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7864                         assert_eq!(msg.data, expected_err);
7865                 }
7866                 _ => panic!("Unexpected event"),
7867         }
7868
7869         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
7870 }
7871
7872 #[test]
7873 fn test_can_not_accept_inbound_channel_twice() {
7874         let mut manually_accept_conf = UserConfig::default();
7875         manually_accept_conf.manually_accept_inbound_channels = true;
7876         let chanmon_cfgs = create_chanmon_cfgs(2);
7877         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7878         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7879         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7880
7881         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7882         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7883
7884         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7885
7886         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7887         // accepting the inbound channel request.
7888         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7889
7890         let events = nodes[1].node.get_and_clear_pending_events();
7891         match events[0] {
7892                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7893                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7894                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7895                         match api_res {
7896                                 Err(APIError::APIMisuseError { err }) => {
7897                                         assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
7898                                 },
7899                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7900                                 Err(_) => panic!("Unexpected Error"),
7901                         }
7902                 }
7903                 _ => panic!("Unexpected event"),
7904         }
7905
7906         // Ensure that the channel wasn't closed after attempting to accept it twice.
7907         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7908         assert_eq!(accept_msg_ev.len(), 1);
7909
7910         match accept_msg_ev[0] {
7911                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7912                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7913                 }
7914                 _ => panic!("Unexpected event"),
7915         }
7916 }
7917
7918 #[test]
7919 fn test_can_not_accept_unknown_inbound_channel() {
7920         let chanmon_cfg = create_chanmon_cfgs(2);
7921         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
7922         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
7923         let nodes = create_network(2, &node_cfg, &node_chanmgr);
7924
7925         let unknown_channel_id = [0; 32];
7926         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
7927         match api_res {
7928                 Err(APIError::ChannelUnavailable { err }) => {
7929                         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()));
7930                 },
7931                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
7932                 Err(_) => panic!("Unexpected Error"),
7933         }
7934 }
7935
7936 #[test]
7937 fn test_onion_value_mpp_set_calculation() {
7938         // Test that we use the onion value `amt_to_forward` when
7939         // calculating whether we've reached the `total_msat` of an MPP
7940         // by having a routing node forward more than `amt_to_forward`
7941         // and checking that the receiving node doesn't generate
7942         // a PaymentClaimable event too early
7943         let node_count = 4;
7944         let chanmon_cfgs = create_chanmon_cfgs(node_count);
7945         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
7946         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
7947         let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
7948
7949         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
7950         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
7951         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
7952         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
7953
7954         let total_msat = 100_000;
7955         let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
7956         let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
7957         let sample_path = route.paths.pop().unwrap();
7958
7959         let mut path_1 = sample_path.clone();
7960         path_1[0].pubkey = nodes[1].node.get_our_node_id();
7961         path_1[0].short_channel_id = chan_1_id;
7962         path_1[1].pubkey = nodes[3].node.get_our_node_id();
7963         path_1[1].short_channel_id = chan_3_id;
7964         path_1[1].fee_msat = 100_000;
7965         route.paths.push(path_1);
7966
7967         let mut path_2 = sample_path.clone();
7968         path_2[0].pubkey = nodes[2].node.get_our_node_id();
7969         path_2[0].short_channel_id = chan_2_id;
7970         path_2[1].pubkey = nodes[3].node.get_our_node_id();
7971         path_2[1].short_channel_id = chan_4_id;
7972         path_2[1].fee_msat = 1_000;
7973         route.paths.push(path_2);
7974
7975         // Send payment
7976         let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
7977         let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(our_payment_secret), payment_id, &route).unwrap();
7978         nodes[0].node.test_send_payment_internal(&route, our_payment_hash, &Some(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
7979         check_added_monitors!(nodes[0], expected_paths.len());
7980
7981         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7982         assert_eq!(events.len(), expected_paths.len());
7983
7984         // First path
7985         let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
7986         let mut payment_event = SendEvent::from_event(ev);
7987         let mut prev_node = &nodes[0];
7988
7989         for (idx, &node) in expected_paths[0].iter().enumerate() {
7990                 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
7991
7992                 if idx == 0 { // routing node
7993                         let session_priv = [3; 32];
7994                         let height = nodes[0].best_block_info().1;
7995                         let session_priv = SecretKey::from_slice(&session_priv).unwrap();
7996                         let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
7997                         let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000, &Some(our_payment_secret), height + 1, &None).unwrap();
7998                         // Edit amt_to_forward to simulate the sender having set
7999                         // the final amount and the routing node taking less fee
8000                         onion_payloads[1].amt_to_forward = 99_000;
8001                         let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
8002                         payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8003                 }
8004
8005                 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8006                 check_added_monitors!(node, 0);
8007                 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8008                 expect_pending_htlcs_forwardable!(node);
8009
8010                 if idx == 0 {
8011                         let mut events_2 = node.node.get_and_clear_pending_msg_events();
8012                         assert_eq!(events_2.len(), 1);
8013                         check_added_monitors!(node, 1);
8014                         payment_event = SendEvent::from_event(events_2.remove(0));
8015                         assert_eq!(payment_event.msgs.len(), 1);
8016                 } else {
8017                         let events_2 = node.node.get_and_clear_pending_events();
8018                         assert!(events_2.is_empty());
8019                 }
8020
8021                 prev_node = node;
8022         }
8023
8024         // Second path
8025         let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8026         pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8027
8028         claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8029 }
8030
8031 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8032
8033         let routing_node_count = msat_amounts.len();
8034         let node_count = routing_node_count + 2;
8035
8036         let chanmon_cfgs = create_chanmon_cfgs(node_count);
8037         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8038         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8039         let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8040
8041         let src_idx = 0;
8042         let dst_idx = 1;
8043
8044         // Create channels for each amount
8045         let mut expected_paths = Vec::with_capacity(routing_node_count);
8046         let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8047         let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8048         for i in 0..routing_node_count {
8049                 let routing_node = 2 + i;
8050                 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8051                 src_chan_ids.push(src_chan_id);
8052                 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8053                 dst_chan_ids.push(dst_chan_id);
8054                 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8055                 expected_paths.push(path);
8056         }
8057         let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8058
8059         // Create a route for each amount
8060         let example_amount = 100000;
8061         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);
8062         let sample_path = route.paths.pop().unwrap();
8063         for i in 0..routing_node_count {
8064                 let routing_node = 2 + i;
8065                 let mut path = sample_path.clone();
8066                 path[0].pubkey = nodes[routing_node].node.get_our_node_id();
8067                 path[0].short_channel_id = src_chan_ids[i];
8068                 path[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8069                 path[1].short_channel_id = dst_chan_ids[i];
8070                 path[1].fee_msat = msat_amounts[i];
8071                 route.paths.push(path);
8072         }
8073
8074         // Send payment with manually set total_msat
8075         let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8076         let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash, Some(our_payment_secret), payment_id, &route).unwrap();
8077         nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash, &Some(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8078         check_added_monitors!(nodes[src_idx], expected_paths.len());
8079
8080         let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8081         assert_eq!(events.len(), expected_paths.len());
8082         let mut amount_received = 0;
8083         for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8084                 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8085
8086                 let current_path_amount = msat_amounts[path_idx];
8087                 amount_received += current_path_amount;
8088                 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8089                 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8090         }
8091
8092         claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8093 }
8094
8095 #[test]
8096 fn test_overshoot_mpp() {
8097         do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8098         do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8099 }
8100
8101 #[test]
8102 fn test_simple_mpp() {
8103         // Simple test of sending a multi-path payment.
8104         let chanmon_cfgs = create_chanmon_cfgs(4);
8105         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8106         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8107         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8108
8109         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8110         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8111         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8112         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8113
8114         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8115         let path = route.paths[0].clone();
8116         route.paths.push(path);
8117         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8118         route.paths[0][0].short_channel_id = chan_1_id;
8119         route.paths[0][1].short_channel_id = chan_3_id;
8120         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8121         route.paths[1][0].short_channel_id = chan_2_id;
8122         route.paths[1][1].short_channel_id = chan_4_id;
8123         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8124         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8125 }
8126
8127 #[test]
8128 fn test_preimage_storage() {
8129         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8130         let chanmon_cfgs = create_chanmon_cfgs(2);
8131         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8132         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8133         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8134
8135         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8136
8137         {
8138                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8139                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8140                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
8141                 check_added_monitors!(nodes[0], 1);
8142                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8143                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8144                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8145                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8146         }
8147         // Note that after leaving the above scope we have no knowledge of any arguments or return
8148         // values from previous calls.
8149         expect_pending_htlcs_forwardable!(nodes[1]);
8150         let events = nodes[1].node.get_and_clear_pending_events();
8151         assert_eq!(events.len(), 1);
8152         match events[0] {
8153                 Event::PaymentClaimable { ref purpose, .. } => {
8154                         match &purpose {
8155                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8156                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8157                                 },
8158                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8159                         }
8160                 },
8161                 _ => panic!("Unexpected event"),
8162         }
8163 }
8164
8165 #[test]
8166 #[allow(deprecated)]
8167 fn test_secret_timeout() {
8168         // Simple test of payment secret storage time outs. After
8169         // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
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         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8178
8179         // We should fail to register the same payment hash twice, at least until we've connected a
8180         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8181         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8182                 assert_eq!(err, "Duplicate payment hash");
8183         } else { panic!(); }
8184         let mut block = {
8185                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8186                 Block {
8187                         header: BlockHeader {
8188                                 version: 0x2000000,
8189                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8190                                 merkle_root: TxMerkleNode::all_zeros(),
8191                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8192                         txdata: vec![],
8193                 }
8194         };
8195         connect_block(&nodes[1], &block);
8196         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8197                 assert_eq!(err, "Duplicate payment hash");
8198         } else { panic!(); }
8199
8200         // If we then connect the second block, we should be able to register the same payment hash
8201         // again (this time getting a new payment secret).
8202         block.header.prev_blockhash = block.header.block_hash();
8203         block.header.time += 1;
8204         connect_block(&nodes[1], &block);
8205         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8206         assert_ne!(payment_secret_1, our_payment_secret);
8207
8208         {
8209                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8210                 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret), PaymentId(payment_hash.0)).unwrap();
8211                 check_added_monitors!(nodes[0], 1);
8212                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8213                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8214                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8215                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8216         }
8217         // Note that after leaving the above scope we have no knowledge of any arguments or return
8218         // values from previous calls.
8219         expect_pending_htlcs_forwardable!(nodes[1]);
8220         let events = nodes[1].node.get_and_clear_pending_events();
8221         assert_eq!(events.len(), 1);
8222         match events[0] {
8223                 Event::PaymentClaimable { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8224                         assert!(payment_preimage.is_none());
8225                         assert_eq!(payment_secret, our_payment_secret);
8226                         // We don't actually have the payment preimage with which to claim this payment!
8227                 },
8228                 _ => panic!("Unexpected event"),
8229         }
8230 }
8231
8232 #[test]
8233 fn test_bad_secret_hash() {
8234         // Simple test of unregistered payment hash/invalid payment secret handling
8235         let chanmon_cfgs = create_chanmon_cfgs(2);
8236         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8237         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8238         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8239
8240         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8241
8242         let random_payment_hash = PaymentHash([42; 32]);
8243         let random_payment_secret = PaymentSecret([43; 32]);
8244         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8245         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8246
8247         // All the below cases should end up being handled exactly identically, so we macro the
8248         // resulting events.
8249         macro_rules! handle_unknown_invalid_payment_data {
8250                 ($payment_hash: expr) => {
8251                         check_added_monitors!(nodes[0], 1);
8252                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8253                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8254                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8255                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8256
8257                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8258                         // again to process the pending backwards-failure of the HTLC
8259                         expect_pending_htlcs_forwardable!(nodes[1]);
8260                         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8261                         check_added_monitors!(nodes[1], 1);
8262
8263                         // We should fail the payment back
8264                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8265                         match events.pop().unwrap() {
8266                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8267                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8268                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8269                                 },
8270                                 _ => panic!("Unexpected event"),
8271                         }
8272                 }
8273         }
8274
8275         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8276         // Error data is the HTLC value (100,000) and current block height
8277         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8278
8279         // Send a payment with the right payment hash but the wrong payment secret
8280         nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8281         handle_unknown_invalid_payment_data!(our_payment_hash);
8282         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8283
8284         // Send a payment with a random payment hash, but the right payment secret
8285         nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8286         handle_unknown_invalid_payment_data!(random_payment_hash);
8287         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8288
8289         // Send a payment with a random payment hash and random payment secret
8290         nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8291         handle_unknown_invalid_payment_data!(random_payment_hash);
8292         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8293 }
8294
8295 #[test]
8296 fn test_update_err_monitor_lockdown() {
8297         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8298         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8299         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8300         // error.
8301         //
8302         // This scenario may happen in a watchtower setup, where watchtower process a block height
8303         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8304         // commitment at same time.
8305
8306         let chanmon_cfgs = create_chanmon_cfgs(2);
8307         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8308         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8309         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8310
8311         // Create some initial channel
8312         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8313         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8314
8315         // Rebalance the network to generate htlc in the two directions
8316         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8317
8318         // Route a HTLC from node 0 to node 1 (but don't settle)
8319         let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8320
8321         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8322         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8323         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8324         let persister = test_utils::TestPersister::new();
8325         let watchtower = {
8326                 let new_monitor = {
8327                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8328                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8329                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8330                         assert!(new_monitor == *monitor);
8331                         new_monitor
8332                 };
8333                 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);
8334                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8335                 watchtower
8336         };
8337         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8338         let block = Block { header, txdata: vec![] };
8339         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8340         // transaction lock time requirements here.
8341         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8342         watchtower.chain_monitor.block_connected(&block, 200);
8343
8344         // Try to update ChannelMonitor
8345         nodes[1].node.claim_funds(preimage);
8346         check_added_monitors!(nodes[1], 1);
8347         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8348
8349         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8350         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8351         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8352         {
8353                 let mut node_0_per_peer_lock;
8354                 let mut node_0_peer_state_lock;
8355                 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8356                 if let Ok(update) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8357                         assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8358                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8359                 } else { assert!(false); }
8360         }
8361         // Our local monitor is in-sync and hasn't processed yet timeout
8362         check_added_monitors!(nodes[0], 1);
8363         let events = nodes[0].node.get_and_clear_pending_events();
8364         assert_eq!(events.len(), 1);
8365 }
8366
8367 #[test]
8368 fn test_concurrent_monitor_claim() {
8369         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8370         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8371         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8372         // state N+1 confirms. Alice claims output from state N+1.
8373
8374         let chanmon_cfgs = create_chanmon_cfgs(2);
8375         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8376         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8377         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8378
8379         // Create some initial channel
8380         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8381         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8382
8383         // Rebalance the network to generate htlc in the two directions
8384         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8385
8386         // Route a HTLC from node 0 to node 1 (but don't settle)
8387         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8388
8389         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8390         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8391         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8392         let persister = test_utils::TestPersister::new();
8393         let watchtower_alice = {
8394                 let new_monitor = {
8395                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8396                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8397                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8398                         assert!(new_monitor == *monitor);
8399                         new_monitor
8400                 };
8401                 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);
8402                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8403                 watchtower
8404         };
8405         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8406         let block = Block { header, txdata: vec![] };
8407         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8408         // transaction lock time requirements here.
8409         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize((CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS) as usize, (block.clone(), 0));
8410         watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8411
8412         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8413         {
8414                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8415                 assert_eq!(txn.len(), 2);
8416                 txn.clear();
8417         }
8418
8419         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8420         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8421         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8422         let persister = test_utils::TestPersister::new();
8423         let watchtower_bob = {
8424                 let new_monitor = {
8425                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8426                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8427                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8428                         assert!(new_monitor == *monitor);
8429                         new_monitor
8430                 };
8431                 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);
8432                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8433                 watchtower
8434         };
8435         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8436         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8437
8438         // Route another payment to generate another update with still previous HTLC pending
8439         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8440         {
8441                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
8442         }
8443         check_added_monitors!(nodes[1], 1);
8444
8445         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8446         assert_eq!(updates.update_add_htlcs.len(), 1);
8447         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8448         {
8449                 let mut node_0_per_peer_lock;
8450                 let mut node_0_peer_state_lock;
8451                 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8452                 if let Ok(update) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8453                         // Watchtower Alice should already have seen the block and reject the update
8454                         assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8455                         assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8456                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8457                 } else { assert!(false); }
8458         }
8459         // Our local monitor is in-sync and hasn't processed yet timeout
8460         check_added_monitors!(nodes[0], 1);
8461
8462         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8463         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8464         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8465
8466         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8467         let bob_state_y;
8468         {
8469                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8470                 assert_eq!(txn.len(), 2);
8471                 bob_state_y = txn[0].clone();
8472                 txn.clear();
8473         };
8474
8475         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8476         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8477         watchtower_alice.chain_monitor.block_connected(&Block { header, txdata: vec![bob_state_y.clone()] }, CHAN_CONFIRM_DEPTH + 2 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8478         {
8479                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8480                 assert_eq!(htlc_txn.len(), 1);
8481                 check_spends!(htlc_txn[0], bob_state_y);
8482         }
8483 }
8484
8485 #[test]
8486 fn test_pre_lockin_no_chan_closed_update() {
8487         // Test that if a peer closes a channel in response to a funding_created message we don't
8488         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8489         // message).
8490         //
8491         // Doing so would imply a channel monitor update before the initial channel monitor
8492         // registration, violating our API guarantees.
8493         //
8494         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8495         // then opening a second channel with the same funding output as the first (which is not
8496         // rejected because the first channel does not exist in the ChannelManager) and closing it
8497         // before receiving funding_signed.
8498         let chanmon_cfgs = create_chanmon_cfgs(2);
8499         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8500         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8501         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8502
8503         // Create an initial channel
8504         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8505         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8506         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8507         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8508         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8509
8510         // Move the first channel through the funding flow...
8511         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8512
8513         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8514         check_added_monitors!(nodes[0], 0);
8515
8516         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8517         let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8518         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8519         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8520         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true);
8521 }
8522
8523 #[test]
8524 fn test_htlc_no_detection() {
8525         // This test is a mutation to underscore the detection logic bug we had
8526         // before #653. HTLC value routed is above the remaining balance, thus
8527         // inverting HTLC and `to_remote` output. HTLC will come second and
8528         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8529         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8530         // outputs order detection for correct spending children filtring.
8531
8532         let chanmon_cfgs = create_chanmon_cfgs(2);
8533         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8534         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8535         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8536
8537         // Create some initial channels
8538         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8539
8540         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8541         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8542         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8543         assert_eq!(local_txn[0].input.len(), 1);
8544         assert_eq!(local_txn[0].output.len(), 3);
8545         check_spends!(local_txn[0], chan_1.3);
8546
8547         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8548         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8549         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8550         // We deliberately connect the local tx twice as this should provoke a failure calling
8551         // this test before #653 fix.
8552         chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &Block { header, txdata: vec![local_txn[0].clone()] }, nodes[0].best_block_info().1 + 1);
8553         check_closed_broadcast!(nodes[0], true);
8554         check_added_monitors!(nodes[0], 1);
8555         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8556         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8557
8558         let htlc_timeout = {
8559                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8560                 assert_eq!(node_txn.len(), 1);
8561                 assert_eq!(node_txn[0].input.len(), 1);
8562                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8563                 check_spends!(node_txn[0], local_txn[0]);
8564                 node_txn[0].clone()
8565         };
8566
8567         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8568         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8569         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8570         expect_payment_failed!(nodes[0], our_payment_hash, false);
8571 }
8572
8573 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8574         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8575         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8576         // Carol, Alice would be the upstream node, and Carol the downstream.)
8577         //
8578         // Steps of the test:
8579         // 1) Alice sends a HTLC to Carol through Bob.
8580         // 2) Carol doesn't settle the HTLC.
8581         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8582         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8583         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8584         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8585         // 5) Carol release the preimage to Bob off-chain.
8586         // 6) Bob claims the offered output on the broadcasted commitment.
8587         let chanmon_cfgs = create_chanmon_cfgs(3);
8588         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8589         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8590         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8591
8592         // Create some initial channels
8593         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8594         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8595
8596         // Steps (1) and (2):
8597         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8598         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8599
8600         // Check that Alice's commitment transaction now contains an output for this HTLC.
8601         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8602         check_spends!(alice_txn[0], chan_ab.3);
8603         assert_eq!(alice_txn[0].output.len(), 2);
8604         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8605         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8606         assert_eq!(alice_txn.len(), 2);
8607
8608         // Steps (3) and (4):
8609         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8610         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8611         let mut force_closing_node = 0; // Alice force-closes
8612         let mut counterparty_node = 1; // Bob if Alice force-closes
8613
8614         // Bob force-closes
8615         if !broadcast_alice {
8616                 force_closing_node = 1;
8617                 counterparty_node = 0;
8618         }
8619         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8620         check_closed_broadcast!(nodes[force_closing_node], true);
8621         check_added_monitors!(nodes[force_closing_node], 1);
8622         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8623         if go_onchain_before_fulfill {
8624                 let txn_to_broadcast = match broadcast_alice {
8625                         true => alice_txn.clone(),
8626                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8627                 };
8628                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8629                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8630                 if broadcast_alice {
8631                         check_closed_broadcast!(nodes[1], true);
8632                         check_added_monitors!(nodes[1], 1);
8633                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8634                 }
8635         }
8636
8637         // Step (5):
8638         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8639         // process of removing the HTLC from their commitment transactions.
8640         nodes[2].node.claim_funds(payment_preimage);
8641         check_added_monitors!(nodes[2], 1);
8642         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8643
8644         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8645         assert!(carol_updates.update_add_htlcs.is_empty());
8646         assert!(carol_updates.update_fail_htlcs.is_empty());
8647         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8648         assert!(carol_updates.update_fee.is_none());
8649         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8650
8651         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8652         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8653         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8654         if !go_onchain_before_fulfill && broadcast_alice {
8655                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8656                 assert_eq!(events.len(), 1);
8657                 match events[0] {
8658                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8659                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8660                         },
8661                         _ => panic!("Unexpected event"),
8662                 };
8663         }
8664         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8665         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8666         // Carol<->Bob's updated commitment transaction info.
8667         check_added_monitors!(nodes[1], 2);
8668
8669         let events = nodes[1].node.get_and_clear_pending_msg_events();
8670         assert_eq!(events.len(), 2);
8671         let bob_revocation = match events[0] {
8672                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8673                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8674                         (*msg).clone()
8675                 },
8676                 _ => panic!("Unexpected event"),
8677         };
8678         let bob_updates = match events[1] {
8679                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8680                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8681                         (*updates).clone()
8682                 },
8683                 _ => panic!("Unexpected event"),
8684         };
8685
8686         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8687         check_added_monitors!(nodes[2], 1);
8688         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8689         check_added_monitors!(nodes[2], 1);
8690
8691         let events = nodes[2].node.get_and_clear_pending_msg_events();
8692         assert_eq!(events.len(), 1);
8693         let carol_revocation = match events[0] {
8694                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8695                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8696                         (*msg).clone()
8697                 },
8698                 _ => panic!("Unexpected event"),
8699         };
8700         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8701         check_added_monitors!(nodes[1], 1);
8702
8703         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8704         // here's where we put said channel's commitment tx on-chain.
8705         let mut txn_to_broadcast = alice_txn.clone();
8706         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8707         if !go_onchain_before_fulfill {
8708                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8709                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8710                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8711                 if broadcast_alice {
8712                         check_closed_broadcast!(nodes[1], true);
8713                         check_added_monitors!(nodes[1], 1);
8714                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8715                 }
8716                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8717                 if broadcast_alice {
8718                         assert_eq!(bob_txn.len(), 1);
8719                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8720                 } else {
8721                         assert_eq!(bob_txn.len(), 2);
8722                         check_spends!(bob_txn[0], chan_ab.3);
8723                 }
8724         }
8725
8726         // Step (6):
8727         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8728         // broadcasted commitment transaction.
8729         {
8730                 let script_weight = match broadcast_alice {
8731                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8732                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8733                 };
8734                 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8735                 // Bob force-closed and broadcasts the commitment transaction along with a
8736                 // HTLC-output-claiming transaction.
8737                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8738                 if broadcast_alice {
8739                         assert_eq!(bob_txn.len(), 1);
8740                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8741                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8742                 } else {
8743                         assert_eq!(bob_txn.len(), 2);
8744                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8745                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8746                 }
8747         }
8748 }
8749
8750 #[test]
8751 fn test_onchain_htlc_settlement_after_close() {
8752         do_test_onchain_htlc_settlement_after_close(true, true);
8753         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8754         do_test_onchain_htlc_settlement_after_close(true, false);
8755         do_test_onchain_htlc_settlement_after_close(false, false);
8756 }
8757
8758 #[test]
8759 fn test_duplicate_temporary_channel_id_from_different_peers() {
8760         // Tests that we can accept two different `OpenChannel` requests with the same
8761         // `temporary_channel_id`, as long as they are from different peers.
8762         let chanmon_cfgs = create_chanmon_cfgs(3);
8763         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8764         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8765         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8766
8767         // Create an first channel channel
8768         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8769         let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8770
8771         // Create an second channel
8772         nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8773         let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8774
8775         // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8776         // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8777         open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8778
8779         // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8780         // `temporary_channel_id` as they are from different peers.
8781         nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8782         {
8783                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8784                 assert_eq!(events.len(), 1);
8785                 match &events[0] {
8786                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8787                                 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8788                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8789                         },
8790                         _ => panic!("Unexpected event"),
8791                 }
8792         }
8793
8794         nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8795         {
8796                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8797                 assert_eq!(events.len(), 1);
8798                 match &events[0] {
8799                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8800                                 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8801                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8802                         },
8803                         _ => panic!("Unexpected event"),
8804                 }
8805         }
8806 }
8807
8808 #[test]
8809 fn test_duplicate_chan_id() {
8810         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8811         // already open we reject it and keep the old channel.
8812         //
8813         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8814         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8815         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8816         // updating logic for the existing channel.
8817         let chanmon_cfgs = create_chanmon_cfgs(2);
8818         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8819         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8820         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8821
8822         // Create an initial channel
8823         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8824         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8825         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8826         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()));
8827
8828         // Try to create a second channel with the same temporary_channel_id as the first and check
8829         // that it is rejected.
8830         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8831         {
8832                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8833                 assert_eq!(events.len(), 1);
8834                 match events[0] {
8835                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8836                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8837                                 // first (valid) and second (invalid) channels are closed, given they both have
8838                                 // the same non-temporary channel_id. However, currently we do not, so we just
8839                                 // move forward with it.
8840                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8841                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8842                         },
8843                         _ => panic!("Unexpected event"),
8844                 }
8845         }
8846
8847         // Move the first channel through the funding flow...
8848         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8849
8850         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8851         check_added_monitors!(nodes[0], 0);
8852
8853         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8854         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8855         {
8856                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8857                 assert_eq!(added_monitors.len(), 1);
8858                 assert_eq!(added_monitors[0].0, funding_output);
8859                 added_monitors.clear();
8860         }
8861         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8862
8863         let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8864         let channel_id = funding_outpoint.to_channel_id();
8865
8866         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8867         // temporary one).
8868
8869         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8870         // Technically this is allowed by the spec, but we don't support it and there's little reason
8871         // to. Still, it shouldn't cause any other issues.
8872         open_chan_msg.temporary_channel_id = channel_id;
8873         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8874         {
8875                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8876                 assert_eq!(events.len(), 1);
8877                 match events[0] {
8878                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8879                                 // Technically, at this point, nodes[1] would be justified in thinking both
8880                                 // channels are closed, but currently we do not, so we just 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         // Now try to create a second channel which has a duplicate funding output.
8889         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8890         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8891         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
8892         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()));
8893         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8894
8895         let funding_created = {
8896                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8897                 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
8898                 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
8899                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8900                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8901                 // channelmanager in a possibly nonsense state instead).
8902                 let mut as_chan = a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8903                 let logger = test_utils::TestLogger::new();
8904                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8905         };
8906         check_added_monitors!(nodes[0], 0);
8907         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8908         // At this point we'll look up if the channel_id is present and immediately fail the channel
8909         // without trying to persist the `ChannelMonitor`.
8910         check_added_monitors!(nodes[1], 0);
8911
8912         // ...still, nodes[1] will reject the duplicate channel.
8913         {
8914                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8915                 assert_eq!(events.len(), 1);
8916                 match events[0] {
8917                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8918                                 // Technically, at this point, nodes[1] would be justified in thinking both
8919                                 // channels are closed, but currently we do not, so we just move forward with it.
8920                                 assert_eq!(msg.channel_id, channel_id);
8921                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8922                         },
8923                         _ => panic!("Unexpected event"),
8924                 }
8925         }
8926
8927         // finally, finish creating the original channel and send a payment over it to make sure
8928         // everything is functional.
8929         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8930         {
8931                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8932                 assert_eq!(added_monitors.len(), 1);
8933                 assert_eq!(added_monitors[0].0, funding_output);
8934                 added_monitors.clear();
8935         }
8936
8937         let events_4 = nodes[0].node.get_and_clear_pending_events();
8938         assert_eq!(events_4.len(), 0);
8939         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8940         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8941
8942         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8943         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
8944         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8945
8946         send_payment(&nodes[0], &[&nodes[1]], 8000000);
8947 }
8948
8949 #[test]
8950 fn test_error_chans_closed() {
8951         // Test that we properly handle error messages, closing appropriate channels.
8952         //
8953         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8954         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8955         // we can test various edge cases around it to ensure we don't regress.
8956         let chanmon_cfgs = create_chanmon_cfgs(3);
8957         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8958         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8959         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8960
8961         // Create some initial channels
8962         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8963         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8964         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
8965
8966         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8967         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8968         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8969
8970         // Closing a channel from a different peer has no effect
8971         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8972         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8973
8974         // Closing one channel doesn't impact others
8975         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8976         check_added_monitors!(nodes[0], 1);
8977         check_closed_broadcast!(nodes[0], false);
8978         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
8979         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8980         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8981         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);
8982         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);
8983
8984         // A null channel ID should close all channels
8985         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8986         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8987         check_added_monitors!(nodes[0], 2);
8988         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
8989         let events = nodes[0].node.get_and_clear_pending_msg_events();
8990         assert_eq!(events.len(), 2);
8991         match events[0] {
8992                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8993                         assert_eq!(msg.contents.flags & 2, 2);
8994                 },
8995                 _ => panic!("Unexpected event"),
8996         }
8997         match events[1] {
8998                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8999                         assert_eq!(msg.contents.flags & 2, 2);
9000                 },
9001                 _ => panic!("Unexpected event"),
9002         }
9003         // Note that at this point users of a standard PeerHandler will end up calling
9004         // peer_disconnected.
9005         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9006         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9007
9008         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9009         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9010         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9011 }
9012
9013 #[test]
9014 fn test_invalid_funding_tx() {
9015         // Test that we properly handle invalid funding transactions sent to us from a peer.
9016         //
9017         // Previously, all other major lightning implementations had failed to properly sanitize
9018         // funding transactions from their counterparties, leading to a multi-implementation critical
9019         // security vulnerability (though we always sanitized properly, we've previously had
9020         // un-released crashes in the sanitization process).
9021         //
9022         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9023         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9024         // gave up on it. We test this here by generating such a transaction.
9025         let chanmon_cfgs = create_chanmon_cfgs(2);
9026         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9027         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9028         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9029
9030         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9031         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()));
9032         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()));
9033
9034         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9035
9036         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9037         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9038         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9039         // its length.
9040         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9041         let wit_program_script: Script = wit_program.into();
9042         for output in tx.output.iter_mut() {
9043                 // Make the confirmed funding transaction have a bogus script_pubkey
9044                 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9045         }
9046
9047         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9048         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()));
9049         check_added_monitors!(nodes[1], 1);
9050
9051         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()));
9052         check_added_monitors!(nodes[0], 1);
9053
9054         let events_1 = nodes[0].node.get_and_clear_pending_events();
9055         assert_eq!(events_1.len(), 0);
9056
9057         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9058         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9059         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9060
9061         let expected_err = "funding tx had wrong script/value or output index";
9062         confirm_transaction_at(&nodes[1], &tx, 1);
9063         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9064         check_added_monitors!(nodes[1], 1);
9065         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9066         assert_eq!(events_2.len(), 1);
9067         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9068                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9069                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9070                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9071                 } else { panic!(); }
9072         } else { panic!(); }
9073         assert_eq!(nodes[1].node.list_channels().len(), 0);
9074
9075         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9076         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9077         // as its not 32 bytes long.
9078         let mut spend_tx = Transaction {
9079                 version: 2i32, lock_time: PackedLockTime::ZERO,
9080                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9081                         previous_output: BitcoinOutPoint {
9082                                 txid: tx.txid(),
9083                                 vout: idx as u32,
9084                         },
9085                         script_sig: Script::new(),
9086                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9087                         witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9088                 }).collect(),
9089                 output: vec![TxOut {
9090                         value: 1000,
9091                         script_pubkey: Script::new(),
9092                 }]
9093         };
9094         check_spends!(spend_tx, tx);
9095         mine_transaction(&nodes[1], &spend_tx);
9096 }
9097
9098 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9099         // In the first version of the chain::Confirm interface, after a refactor was made to not
9100         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9101         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9102         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9103         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9104         // spending transaction until height N+1 (or greater). This was due to the way
9105         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9106         // spending transaction at the height the input transaction was confirmed at, not whether we
9107         // should broadcast a spending transaction at the current height.
9108         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9109         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9110         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9111         // until we learned about an additional block.
9112         //
9113         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9114         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9115         let chanmon_cfgs = create_chanmon_cfgs(3);
9116         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9117         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9118         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9119         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9120
9121         create_announced_chan_between_nodes(&nodes, 0, 1);
9122         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9123         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9124         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9125         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9126
9127         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9128         check_closed_broadcast!(nodes[1], true);
9129         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9130         check_added_monitors!(nodes[1], 1);
9131         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9132         assert_eq!(node_txn.len(), 1);
9133
9134         let conf_height = nodes[1].best_block_info().1;
9135         if !test_height_before_timelock {
9136                 connect_blocks(&nodes[1], 24 * 6);
9137         }
9138         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9139                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9140         if test_height_before_timelock {
9141                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9142                 // generate any events or broadcast any transactions
9143                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9144                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9145         } else {
9146                 // We should broadcast an HTLC transaction spending our funding transaction first
9147                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9148                 assert_eq!(spending_txn.len(), 2);
9149                 assert_eq!(spending_txn[0], node_txn[0]);
9150                 check_spends!(spending_txn[1], node_txn[0]);
9151                 // We should also generate a SpendableOutputs event with the to_self output (as its
9152                 // timelock is up).
9153                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9154                 assert_eq!(descriptor_spend_txn.len(), 1);
9155
9156                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9157                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9158                 // additional block built on top of the current chain.
9159                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9160                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9161                 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 }]);
9162                 check_added_monitors!(nodes[1], 1);
9163
9164                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9165                 assert!(updates.update_add_htlcs.is_empty());
9166                 assert!(updates.update_fulfill_htlcs.is_empty());
9167                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9168                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9169                 assert!(updates.update_fee.is_none());
9170                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9171                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9172                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9173         }
9174 }
9175
9176 #[test]
9177 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9178         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9179         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9180 }
9181
9182 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9183         let chanmon_cfgs = create_chanmon_cfgs(2);
9184         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9185         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9186         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9187
9188         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9189
9190         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9191                 .with_features(nodes[1].node.invoice_features());
9192         let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9193
9194         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9195
9196         {
9197                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9198                 check_added_monitors!(nodes[0], 1);
9199                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9200                 assert_eq!(events.len(), 1);
9201                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9202                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9203                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9204         }
9205         expect_pending_htlcs_forwardable!(nodes[1]);
9206         expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9207
9208         {
9209                 // Note that we use a different PaymentId here to allow us to duplicativly pay
9210                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9211                 check_added_monitors!(nodes[0], 1);
9212                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9213                 assert_eq!(events.len(), 1);
9214                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9215                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9216                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9217                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9218                 // assume the second is a privacy attack (no longer particularly relevant
9219                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9220                 // the first HTLC delivered above.
9221         }
9222
9223         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9224         nodes[1].node.process_pending_htlc_forwards();
9225
9226         if test_for_second_fail_panic {
9227                 // Now we go fail back the first HTLC from the user end.
9228                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9229
9230                 let expected_destinations = vec![
9231                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9232                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9233                 ];
9234                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],  expected_destinations);
9235                 nodes[1].node.process_pending_htlc_forwards();
9236
9237                 check_added_monitors!(nodes[1], 1);
9238                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9239                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9240
9241                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9242                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9243                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9244
9245                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9246                 assert_eq!(failure_events.len(), 4);
9247                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9248                 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9249                 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9250                 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9251         } else {
9252                 // Let the second HTLC fail and claim the first
9253                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9254                 nodes[1].node.process_pending_htlc_forwards();
9255
9256                 check_added_monitors!(nodes[1], 1);
9257                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9258                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9259                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9260
9261                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9262
9263                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9264         }
9265 }
9266
9267 #[test]
9268 fn test_dup_htlc_second_fail_panic() {
9269         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9270         // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9271         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9272         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9273         do_test_dup_htlc_second_rejected(true);
9274 }
9275
9276 #[test]
9277 fn test_dup_htlc_second_rejected() {
9278         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9279         // simply reject the second HTLC but are still able to claim the first HTLC.
9280         do_test_dup_htlc_second_rejected(false);
9281 }
9282
9283 #[test]
9284 fn test_inconsistent_mpp_params() {
9285         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9286         // such HTLC and allow the second to stay.
9287         let chanmon_cfgs = create_chanmon_cfgs(4);
9288         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9289         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9290         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9291
9292         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9293         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9294         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9295         let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9296
9297         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9298                 .with_features(nodes[3].node.invoice_features());
9299         let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9300         assert_eq!(route.paths.len(), 2);
9301         route.paths.sort_by(|path_a, _| {
9302                 // Sort the path so that the path through nodes[1] comes first
9303                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9304                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9305         });
9306
9307         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9308
9309         let cur_height = nodes[0].best_block_info().1;
9310         let payment_id = PaymentId([42; 32]);
9311
9312         let session_privs = {
9313                 // We create a fake route here so that we start with three pending HTLCs, which we'll
9314                 // ultimately have, just not right away.
9315                 let mut dup_route = route.clone();
9316                 dup_route.paths.push(route.paths[1].clone());
9317                 nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(our_payment_secret), payment_id, &dup_route).unwrap()
9318         };
9319         nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(our_payment_secret), 15_000_000, cur_height, payment_id, &None, session_privs[0]).unwrap();
9320         check_added_monitors!(nodes[0], 1);
9321
9322         {
9323                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9324                 assert_eq!(events.len(), 1);
9325                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9326         }
9327         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9328
9329         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash, &Some(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9330         check_added_monitors!(nodes[0], 1);
9331
9332         {
9333                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9334                 assert_eq!(events.len(), 1);
9335                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9336
9337                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9338                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9339
9340                 expect_pending_htlcs_forwardable!(nodes[2]);
9341                 check_added_monitors!(nodes[2], 1);
9342
9343                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9344                 assert_eq!(events.len(), 1);
9345                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9346
9347                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9348                 check_added_monitors!(nodes[3], 0);
9349                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9350
9351                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9352                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9353                 // post-payment_secrets) and fail back the new HTLC.
9354         }
9355         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9356         nodes[3].node.process_pending_htlc_forwards();
9357         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9358         nodes[3].node.process_pending_htlc_forwards();
9359
9360         check_added_monitors!(nodes[3], 1);
9361
9362         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9363         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9364         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9365
9366         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 }]);
9367         check_added_monitors!(nodes[2], 1);
9368
9369         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9370         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9371         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9372
9373         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9374
9375         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash, &Some(our_payment_secret), 15_000_000, cur_height, payment_id, &None, session_privs[2]).unwrap();
9376         check_added_monitors!(nodes[0], 1);
9377
9378         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9379         assert_eq!(events.len(), 1);
9380         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9381
9382         do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9383         let events = nodes[0].node.get_and_clear_pending_events();
9384         assert_eq!(events.len(), 3);
9385         match events[0] {
9386                 Event::PaymentSent { payment_hash, .. } => { // The payment was abandoned earlier, so the fee paid will be None
9387                         assert_eq!(payment_hash, our_payment_hash);
9388                 },
9389                 _ => panic!("Unexpected event")
9390         }
9391         match events[1] {
9392                 Event::PaymentPathSuccessful { payment_hash, .. } => {
9393                         assert_eq!(payment_hash.unwrap(), our_payment_hash);
9394                 },
9395                 _ => panic!("Unexpected event")
9396         }
9397         match events[2] {
9398                 Event::PaymentPathSuccessful { payment_hash, .. } => {
9399                         assert_eq!(payment_hash.unwrap(), our_payment_hash);
9400                 },
9401                 _ => panic!("Unexpected event")
9402         }
9403 }
9404
9405 #[test]
9406 fn test_keysend_payments_to_public_node() {
9407         let chanmon_cfgs = create_chanmon_cfgs(2);
9408         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9409         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9410         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9411
9412         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9413         let network_graph = nodes[0].network_graph.clone();
9414         let payer_pubkey = nodes[0].node.get_our_node_id();
9415         let payee_pubkey = nodes[1].node.get_our_node_id();
9416         let route_params = RouteParameters {
9417                 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9418                 final_value_msat: 10000,
9419         };
9420         let scorer = test_utils::TestScorer::new();
9421         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9422         let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9423
9424         let test_preimage = PaymentPreimage([42; 32]);
9425         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage), PaymentId(test_preimage.0)).unwrap();
9426         check_added_monitors!(nodes[0], 1);
9427         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9428         assert_eq!(events.len(), 1);
9429         let event = events.pop().unwrap();
9430         let path = vec![&nodes[1]];
9431         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9432         claim_payment(&nodes[0], &path, test_preimage);
9433 }
9434
9435 #[test]
9436 fn test_keysend_payments_to_private_node() {
9437         let chanmon_cfgs = create_chanmon_cfgs(2);
9438         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9439         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9440         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9441
9442         let payer_pubkey = nodes[0].node.get_our_node_id();
9443         let payee_pubkey = nodes[1].node.get_our_node_id();
9444
9445         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
9446         let route_params = RouteParameters {
9447                 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9448                 final_value_msat: 10000,
9449         };
9450         let network_graph = nodes[0].network_graph.clone();
9451         let first_hops = nodes[0].node.list_usable_channels();
9452         let scorer = test_utils::TestScorer::new();
9453         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9454         let route = find_route(
9455                 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9456                 nodes[0].logger, &scorer, &random_seed_bytes
9457         ).unwrap();
9458
9459         let test_preimage = PaymentPreimage([42; 32]);
9460         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage), PaymentId(test_preimage.0)).unwrap();
9461         check_added_monitors!(nodes[0], 1);
9462         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9463         assert_eq!(events.len(), 1);
9464         let event = events.pop().unwrap();
9465         let path = vec![&nodes[1]];
9466         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9467         claim_payment(&nodes[0], &path, test_preimage);
9468 }
9469
9470 #[test]
9471 fn test_double_partial_claim() {
9472         // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9473         // time out, the sender resends only some of the MPP parts, then the user processes the
9474         // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9475         // amount.
9476         let chanmon_cfgs = create_chanmon_cfgs(4);
9477         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9478         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9479         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9480
9481         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9482         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9483         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9484         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9485
9486         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9487         assert_eq!(route.paths.len(), 2);
9488         route.paths.sort_by(|path_a, _| {
9489                 // Sort the path so that the path through nodes[1] comes first
9490                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9491                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9492         });
9493
9494         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9495         // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9496         // amount of time to respond to.
9497
9498         // Connect some blocks to time out the payment
9499         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9500         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9501
9502         let failed_destinations = vec![
9503                 HTLCDestination::FailedPayment { payment_hash },
9504                 HTLCDestination::FailedPayment { payment_hash },
9505         ];
9506         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9507
9508         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
9509
9510         // nodes[1] now retries one of the two paths...
9511         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9512         check_added_monitors!(nodes[0], 2);
9513
9514         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9515         assert_eq!(events.len(), 2);
9516         let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9517         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9518
9519         // At this point nodes[3] has received one half of the payment, and the user goes to handle
9520         // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9521         nodes[3].node.claim_funds(payment_preimage);
9522         check_added_monitors!(nodes[3], 0);
9523         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9524 }
9525
9526 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9527 #[derive(Clone, Copy, PartialEq)]
9528 enum ExposureEvent {
9529         /// Breach occurs at HTLC forwarding (see `send_htlc`)
9530         AtHTLCForward,
9531         /// Breach occurs at HTLC reception (see `update_add_htlc`)
9532         AtHTLCReception,
9533         /// Breach occurs at outbound update_fee (see `send_update_fee`)
9534         AtUpdateFeeOutbound,
9535 }
9536
9537 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9538         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9539         // policy.
9540         //
9541         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9542         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9543         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9544         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9545         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9546         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9547         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9548         // might be available again for HTLC processing once the dust bandwidth has cleared up.
9549
9550         let chanmon_cfgs = create_chanmon_cfgs(2);
9551         let mut config = test_default_channel_config();
9552         config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9553         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9554         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9555         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9556
9557         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9558         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9559         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9560         open_channel.max_accepted_htlcs = 60;
9561         if on_holder_tx {
9562                 open_channel.dust_limit_satoshis = 546;
9563         }
9564         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9565         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9566         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9567
9568         let opt_anchors = false;
9569
9570         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9571
9572         if on_holder_tx {
9573                 let mut node_0_per_peer_lock;
9574                 let mut node_0_peer_state_lock;
9575                 let mut chan = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id);
9576                 chan.holder_dust_limit_satoshis = 546;
9577         }
9578
9579         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9580         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()));
9581         check_added_monitors!(nodes[1], 1);
9582
9583         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()));
9584         check_added_monitors!(nodes[0], 1);
9585
9586         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9587         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9588         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9589
9590         let dust_buffer_feerate = {
9591                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9592                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9593                 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9594                 chan.get_dust_buffer_feerate(None) as u64
9595         };
9596         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;
9597         let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9598
9599         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;
9600         let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9601
9602         let dust_htlc_on_counterparty_tx: u64 = 25;
9603         let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9604
9605         if on_holder_tx {
9606                 if dust_outbound_balance {
9607                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9608                         // Outbound dust balance: 4372 sats
9609                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9610                         for i in 0..dust_outbound_htlc_on_holder_tx {
9611                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9612                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)) { panic!("Unexpected event at dust HTLC {}", i); }
9613                         }
9614                 } else {
9615                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9616                         // Inbound dust balance: 4372 sats
9617                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9618                         for _ in 0..dust_inbound_htlc_on_holder_tx {
9619                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9620                         }
9621                 }
9622         } else {
9623                 if dust_outbound_balance {
9624                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9625                         // Outbound dust balance: 5000 sats
9626                         for i in 0..dust_htlc_on_counterparty_tx {
9627                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9628                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)) { panic!("Unexpected event at dust HTLC {}", i); }
9629                         }
9630                 } else {
9631                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9632                         // Inbound dust balance: 5000 sats
9633                         for _ in 0..dust_htlc_on_counterparty_tx {
9634                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9635                         }
9636                 }
9637         }
9638
9639         let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9640         if exposure_breach_event == ExposureEvent::AtHTLCForward {
9641                 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 });
9642                 let mut config = UserConfig::default();
9643                 // With default dust exposure: 5000 sats
9644                 if on_holder_tx {
9645                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9646                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9647                         unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)), true, APIError::ChannelUnavailable { ref err }, assert_eq!(err, &format!("Cannot send value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", if dust_outbound_balance { dust_outbound_overflow } else { dust_inbound_overflow }, config.channel_config.max_dust_htlc_exposure_msat)));
9648                 } else {
9649                         unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)), true, APIError::ChannelUnavailable { ref err }, assert_eq!(err, &format!("Cannot send value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx", dust_overflow, config.channel_config.max_dust_htlc_exposure_msat)));
9650                 }
9651         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9652                 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 });
9653                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9654                 check_added_monitors!(nodes[1], 1);
9655                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9656                 assert_eq!(events.len(), 1);
9657                 let payment_event = SendEvent::from_event(events.remove(0));
9658                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9659                 // With default dust exposure: 5000 sats
9660                 if on_holder_tx {
9661                         // Outbound dust balance: 6399 sats
9662                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9663                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9664                         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);
9665                 } else {
9666                         // Outbound dust balance: 5200 sats
9667                         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);
9668                 }
9669         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9670                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
9671                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
9672                 {
9673                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9674                         *feerate_lock = *feerate_lock * 10;
9675                 }
9676                 nodes[0].node.timer_tick_occurred();
9677                 check_added_monitors!(nodes[0], 1);
9678                 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9679         }
9680
9681         let _ = nodes[0].node.get_and_clear_pending_msg_events();
9682         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9683         added_monitors.clear();
9684 }
9685
9686 #[test]
9687 fn test_max_dust_htlc_exposure() {
9688         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9689         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9690         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9691         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9692         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9693         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9694         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9695         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9696         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9697         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9698         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9699         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
9700 }
9701
9702 #[test]
9703 fn test_non_final_funding_tx() {
9704         let chanmon_cfgs = create_chanmon_cfgs(2);
9705         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9706         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9707         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9708
9709         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9710         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9711         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9712         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9713         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9714
9715         let best_height = nodes[0].node.best_block.read().unwrap().height();
9716
9717         let chan_id = *nodes[0].network_chan_count.borrow();
9718         let events = nodes[0].node.get_and_clear_pending_events();
9719         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9720         assert_eq!(events.len(), 1);
9721         let mut tx = match events[0] {
9722                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9723                         // Timelock the transaction _beyond_ the best client height + 2.
9724                         Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 3), input: vec![input], output: vec![TxOut {
9725                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9726                         }]}
9727                 },
9728                 _ => panic!("Unexpected event"),
9729         };
9730         // Transaction should fail as it's evaluated as non-final for propagation.
9731         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9732                 Err(APIError::APIMisuseError { err }) => {
9733                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9734                 },
9735                 _ => panic!()
9736         }
9737
9738         // However, transaction should be accepted if it's in a +2 headroom from best block.
9739         tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9740         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9741         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9742 }
9743
9744 #[test]
9745 fn accept_busted_but_better_fee() {
9746         // If a peer sends us a fee update that is too low, but higher than our previous channel
9747         // feerate, we should accept it. In the future we may want to consider closing the channel
9748         // later, but for now we only accept the update.
9749         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9750         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9751         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9752         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9753
9754         create_chan_between_nodes(&nodes[0], &nodes[1]);
9755
9756         // Set nodes[1] to expect 5,000 sat/kW.
9757         {
9758                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9759                 *feerate_lock = 5000;
9760         }
9761
9762         // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9763         {
9764                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9765                 *feerate_lock = 1000;
9766         }
9767         nodes[0].node.timer_tick_occurred();
9768         check_added_monitors!(nodes[0], 1);
9769
9770         let events = nodes[0].node.get_and_clear_pending_msg_events();
9771         assert_eq!(events.len(), 1);
9772         match events[0] {
9773                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9774                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9775                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9776                 },
9777                 _ => panic!("Unexpected event"),
9778         };
9779
9780         // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9781         // it.
9782         {
9783                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9784                 *feerate_lock = 2000;
9785         }
9786         nodes[0].node.timer_tick_occurred();
9787         check_added_monitors!(nodes[0], 1);
9788
9789         let events = nodes[0].node.get_and_clear_pending_msg_events();
9790         assert_eq!(events.len(), 1);
9791         match events[0] {
9792                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9793                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9794                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9795                 },
9796                 _ => panic!("Unexpected event"),
9797         };
9798
9799         // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9800         // channel.
9801         {
9802                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9803                 *feerate_lock = 1000;
9804         }
9805         nodes[0].node.timer_tick_occurred();
9806         check_added_monitors!(nodes[0], 1);
9807
9808         let events = nodes[0].node.get_and_clear_pending_msg_events();
9809         assert_eq!(events.len(), 1);
9810         match events[0] {
9811                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9812                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9813                         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9814                                 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() });
9815                         check_closed_broadcast!(nodes[1], true);
9816                         check_added_monitors!(nodes[1], 1);
9817                 },
9818                 _ => panic!("Unexpected event"),
9819         };
9820 }
9821
9822 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9823         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9824         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9825         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9826         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9827         let min_final_cltv_expiry_delta = 120;
9828         let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9829                 min_final_cltv_expiry_delta - 2 };
9830         let recv_value = 100_000;
9831
9832         create_chan_between_nodes(&nodes[0], &nodes[1]);
9833
9834         let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
9835         let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
9836                 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
9837                         Some(recv_value), Some(min_final_cltv_expiry_delta));
9838                 (payment_hash, payment_preimage, payment_secret)
9839         } else {
9840                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
9841                 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
9842         };
9843         let route = get_route!(nodes[0], payment_parameters, recv_value, final_cltv_expiry_delta as u32).unwrap();
9844         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9845         check_added_monitors!(nodes[0], 1);
9846         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9847         assert_eq!(events.len(), 1);
9848         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9849         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9850         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9851         expect_pending_htlcs_forwardable!(nodes[1]);
9852
9853         if valid_delta {
9854                 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
9855                         None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
9856
9857                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9858         } else {
9859                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9860
9861                 check_added_monitors!(nodes[1], 1);
9862
9863                 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9864                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
9865                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
9866
9867                 expect_payment_failed!(nodes[0], payment_hash, true);
9868         }
9869 }
9870
9871 #[test]
9872 fn test_payment_with_custom_min_cltv_expiry_delta() {
9873         do_payment_with_custom_min_final_cltv_expiry(false, false);
9874         do_payment_with_custom_min_final_cltv_expiry(false, true);
9875         do_payment_with_custom_min_final_cltv_expiry(true, false);
9876         do_payment_with_custom_min_final_cltv_expiry(true, true);
9877 }