Merge pull request #2136 from marctyndel/2023-03-paymentforwarded-expose-amount-forwarded
[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         };
740
741         let update_fee = msgs::UpdateFee {
742                 channel_id: chan.2,
743                 feerate_per_kw: non_buffer_feerate + 4,
744         };
745
746         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
747
748         //While producing the commitment_signed response after handling a received update_fee request the
749         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
750         //Should produce and error.
751         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
752         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
753         check_added_monitors!(nodes[1], 1);
754         check_closed_broadcast!(nodes[1], true);
755         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
756 }
757
758 #[test]
759 fn test_update_fee_with_fundee_update_add_htlc() {
760         let chanmon_cfgs = create_chanmon_cfgs(2);
761         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
762         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
763         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
764         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
765
766         // balancing
767         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
768
769         {
770                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
771                 *feerate_lock += 20;
772         }
773         nodes[0].node.timer_tick_occurred();
774         check_added_monitors!(nodes[0], 1);
775
776         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
777         assert_eq!(events_0.len(), 1);
778         let (update_msg, commitment_signed) = match events_0[0] {
779                         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 } } => {
780                         (update_fee.as_ref(), commitment_signed)
781                 },
782                 _ => panic!("Unexpected event"),
783         };
784         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
785         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
786         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
787         check_added_monitors!(nodes[1], 1);
788
789         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
790
791         // nothing happens since node[1] is in AwaitingRemoteRevoke
792         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
793         {
794                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
795                 assert_eq!(added_monitors.len(), 0);
796                 added_monitors.clear();
797         }
798         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
799         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
800         // node[1] has nothing to do
801
802         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
803         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
804         check_added_monitors!(nodes[0], 1);
805
806         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
807         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
808         // No commitment_signed so get_event_msg's assert(len == 1) passes
809         check_added_monitors!(nodes[0], 1);
810         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
811         check_added_monitors!(nodes[1], 1);
812         // AwaitingRemoteRevoke ends here
813
814         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
815         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
816         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
817         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
818         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
819         assert_eq!(commitment_update.update_fee.is_none(), true);
820
821         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
822         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
823         check_added_monitors!(nodes[0], 1);
824         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
825
826         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
827         check_added_monitors!(nodes[1], 1);
828         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
829
830         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
831         check_added_monitors!(nodes[1], 1);
832         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
833         // No commitment_signed so get_event_msg's assert(len == 1) passes
834
835         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
836         check_added_monitors!(nodes[0], 1);
837         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
838
839         expect_pending_htlcs_forwardable!(nodes[0]);
840
841         let events = nodes[0].node.get_and_clear_pending_events();
842         assert_eq!(events.len(), 1);
843         match events[0] {
844                 Event::PaymentClaimable { .. } => { },
845                 _ => panic!("Unexpected event"),
846         };
847
848         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
849
850         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
851         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
852         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
853         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
854         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
855 }
856
857 #[test]
858 fn test_update_fee() {
859         let chanmon_cfgs = create_chanmon_cfgs(2);
860         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
861         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
862         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
863         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
864         let channel_id = chan.2;
865
866         // A                                        B
867         // (1) update_fee/commitment_signed      ->
868         //                                       <- (2) revoke_and_ack
869         //                                       .- send (3) commitment_signed
870         // (4) update_fee/commitment_signed      ->
871         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
872         //                                       <- (3) commitment_signed delivered
873         // send (6) revoke_and_ack               -.
874         //                                       <- (5) deliver revoke_and_ack
875         // (6) deliver revoke_and_ack            ->
876         //                                       .- send (7) commitment_signed in response to (4)
877         //                                       <- (7) deliver commitment_signed
878         // revoke_and_ack                        ->
879
880         // Create and deliver (1)...
881         let feerate;
882         {
883                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
884                 feerate = *feerate_lock;
885                 *feerate_lock = feerate + 20;
886         }
887         nodes[0].node.timer_tick_occurred();
888         check_added_monitors!(nodes[0], 1);
889
890         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
891         assert_eq!(events_0.len(), 1);
892         let (update_msg, commitment_signed) = match events_0[0] {
893                         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 } } => {
894                         (update_fee.as_ref(), commitment_signed)
895                 },
896                 _ => panic!("Unexpected event"),
897         };
898         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
899
900         // Generate (2) and (3):
901         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
902         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
903         check_added_monitors!(nodes[1], 1);
904
905         // Deliver (2):
906         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
907         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
908         check_added_monitors!(nodes[0], 1);
909
910         // Create and deliver (4)...
911         {
912                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
913                 *feerate_lock = feerate + 30;
914         }
915         nodes[0].node.timer_tick_occurred();
916         check_added_monitors!(nodes[0], 1);
917         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
918         assert_eq!(events_0.len(), 1);
919         let (update_msg, commitment_signed) = match events_0[0] {
920                         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 } } => {
921                         (update_fee.as_ref(), commitment_signed)
922                 },
923                 _ => panic!("Unexpected event"),
924         };
925
926         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
927         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
928         check_added_monitors!(nodes[1], 1);
929         // ... creating (5)
930         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
931         // No commitment_signed so get_event_msg's assert(len == 1) passes
932
933         // Handle (3), creating (6):
934         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
935         check_added_monitors!(nodes[0], 1);
936         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
937         // No commitment_signed so get_event_msg's assert(len == 1) passes
938
939         // Deliver (5):
940         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
941         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
942         check_added_monitors!(nodes[0], 1);
943
944         // Deliver (6), creating (7):
945         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
946         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
947         assert!(commitment_update.update_add_htlcs.is_empty());
948         assert!(commitment_update.update_fulfill_htlcs.is_empty());
949         assert!(commitment_update.update_fail_htlcs.is_empty());
950         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
951         assert!(commitment_update.update_fee.is_none());
952         check_added_monitors!(nodes[1], 1);
953
954         // Deliver (7)
955         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
956         check_added_monitors!(nodes[0], 1);
957         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
958         // No commitment_signed so get_event_msg's assert(len == 1) passes
959
960         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
961         check_added_monitors!(nodes[1], 1);
962         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
963
964         assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
965         assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
966         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
967         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
968         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
969 }
970
971 #[test]
972 fn fake_network_test() {
973         // Simple test which builds a network of ChannelManagers, connects them to each other, and
974         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
975         let chanmon_cfgs = create_chanmon_cfgs(4);
976         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
977         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
978         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
979
980         // Create some initial channels
981         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
982         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
983         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
984
985         // Rebalance the network a bit by relaying one payment through all the channels...
986         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
987         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
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
991         // Send some more payments
992         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
993         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
994         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
995
996         // Test failure packets
997         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
998         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
999
1000         // Add a new channel that skips 3
1001         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1002
1003         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1004         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1005         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1006         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
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
1011         // Do some rebalance loop payments, simultaneously
1012         let mut hops = Vec::with_capacity(3);
1013         hops.push(RouteHop {
1014                 pubkey: nodes[2].node.get_our_node_id(),
1015                 node_features: NodeFeatures::empty(),
1016                 short_channel_id: chan_2.0.contents.short_channel_id,
1017                 channel_features: ChannelFeatures::empty(),
1018                 fee_msat: 0,
1019                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1020         });
1021         hops.push(RouteHop {
1022                 pubkey: nodes[3].node.get_our_node_id(),
1023                 node_features: NodeFeatures::empty(),
1024                 short_channel_id: chan_3.0.contents.short_channel_id,
1025                 channel_features: ChannelFeatures::empty(),
1026                 fee_msat: 0,
1027                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1028         });
1029         hops.push(RouteHop {
1030                 pubkey: nodes[1].node.get_our_node_id(),
1031                 node_features: nodes[1].node.node_features(),
1032                 short_channel_id: chan_4.0.contents.short_channel_id,
1033                 channel_features: nodes[1].node.channel_features(),
1034                 fee_msat: 1000000,
1035                 cltv_expiry_delta: TEST_FINAL_CLTV,
1036         });
1037         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;
1038         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;
1039         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;
1040
1041         let mut hops = Vec::with_capacity(3);
1042         hops.push(RouteHop {
1043                 pubkey: nodes[3].node.get_our_node_id(),
1044                 node_features: NodeFeatures::empty(),
1045                 short_channel_id: chan_4.0.contents.short_channel_id,
1046                 channel_features: ChannelFeatures::empty(),
1047                 fee_msat: 0,
1048                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1049         });
1050         hops.push(RouteHop {
1051                 pubkey: nodes[2].node.get_our_node_id(),
1052                 node_features: NodeFeatures::empty(),
1053                 short_channel_id: chan_3.0.contents.short_channel_id,
1054                 channel_features: ChannelFeatures::empty(),
1055                 fee_msat: 0,
1056                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1057         });
1058         hops.push(RouteHop {
1059                 pubkey: nodes[1].node.get_our_node_id(),
1060                 node_features: nodes[1].node.node_features(),
1061                 short_channel_id: chan_2.0.contents.short_channel_id,
1062                 channel_features: nodes[1].node.channel_features(),
1063                 fee_msat: 1000000,
1064                 cltv_expiry_delta: TEST_FINAL_CLTV,
1065         });
1066         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;
1067         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;
1068         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;
1069
1070         // Claim the rebalances...
1071         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1072         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1073
1074         // Close down the channels...
1075         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1076         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1077         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1078         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1079         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1080         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1081         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1082         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1083         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1084         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1085         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1086         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1087 }
1088
1089 #[test]
1090 fn holding_cell_htlc_counting() {
1091         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1092         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1093         // commitment dance rounds.
1094         let chanmon_cfgs = create_chanmon_cfgs(3);
1095         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1096         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1097         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1098         create_announced_chan_between_nodes(&nodes, 0, 1);
1099         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1100
1101         let mut payments = Vec::new();
1102         for _ in 0..crate::ln::channel::OUR_MAX_HTLCS {
1103                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1104                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
1105                 payments.push((payment_preimage, payment_hash));
1106         }
1107         check_added_monitors!(nodes[1], 1);
1108
1109         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1110         assert_eq!(events.len(), 1);
1111         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1112         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1113
1114         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1115         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1116         // another HTLC.
1117         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1118         {
1119                 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 },
1120                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1121                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1122                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
1123         }
1124
1125         // This should also be true if we try to forward a payment.
1126         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1127         {
1128                 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1129                 check_added_monitors!(nodes[0], 1);
1130         }
1131
1132         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1133         assert_eq!(events.len(), 1);
1134         let payment_event = SendEvent::from_event(events.pop().unwrap());
1135         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1136
1137         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1138         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1139         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1140         // fails), the second will process the resulting failure and fail the HTLC backward.
1141         expect_pending_htlcs_forwardable!(nodes[1]);
1142         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 }]);
1143         check_added_monitors!(nodes[1], 1);
1144
1145         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1146         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1147         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1148
1149         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1150
1151         // Now forward all the pending HTLCs and claim them back
1152         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1153         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1154         check_added_monitors!(nodes[2], 1);
1155
1156         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1157         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1158         check_added_monitors!(nodes[1], 1);
1159         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1160
1161         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1162         check_added_monitors!(nodes[1], 1);
1163         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1164
1165         for ref update in as_updates.update_add_htlcs.iter() {
1166                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1167         }
1168         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1169         check_added_monitors!(nodes[2], 1);
1170         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1171         check_added_monitors!(nodes[2], 1);
1172         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1173
1174         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1175         check_added_monitors!(nodes[1], 1);
1176         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1177         check_added_monitors!(nodes[1], 1);
1178         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1179
1180         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1181         check_added_monitors!(nodes[2], 1);
1182
1183         expect_pending_htlcs_forwardable!(nodes[2]);
1184
1185         let events = nodes[2].node.get_and_clear_pending_events();
1186         assert_eq!(events.len(), payments.len());
1187         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1188                 match event {
1189                         &Event::PaymentClaimable { ref payment_hash, .. } => {
1190                                 assert_eq!(*payment_hash, *hash);
1191                         },
1192                         _ => panic!("Unexpected event"),
1193                 };
1194         }
1195
1196         for (preimage, _) in payments.drain(..) {
1197                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1198         }
1199
1200         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1201 }
1202
1203 #[test]
1204 fn duplicate_htlc_test() {
1205         // Test that we accept duplicate payment_hash HTLCs across the network and that
1206         // claiming/failing them are all separate and don't affect each other
1207         let chanmon_cfgs = create_chanmon_cfgs(6);
1208         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1209         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1210         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1211
1212         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1213         create_announced_chan_between_nodes(&nodes, 0, 3);
1214         create_announced_chan_between_nodes(&nodes, 1, 3);
1215         create_announced_chan_between_nodes(&nodes, 2, 3);
1216         create_announced_chan_between_nodes(&nodes, 3, 4);
1217         create_announced_chan_between_nodes(&nodes, 3, 5);
1218
1219         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1220
1221         *nodes[0].network_payment_count.borrow_mut() -= 1;
1222         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1223
1224         *nodes[0].network_payment_count.borrow_mut() -= 1;
1225         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1226
1227         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1228         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1229         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1230 }
1231
1232 #[test]
1233 fn test_duplicate_htlc_different_direction_onchain() {
1234         // Test that ChannelMonitor doesn't generate 2 preimage txn
1235         // when we have 2 HTLCs with same preimage that go across a node
1236         // in opposite directions, even with the same payment secret.
1237         let chanmon_cfgs = create_chanmon_cfgs(2);
1238         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1239         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1240         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1241
1242         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1243
1244         // balancing
1245         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1246
1247         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1248
1249         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1250         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1251         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1252
1253         // Provide preimage to node 0 by claiming payment
1254         nodes[0].node.claim_funds(payment_preimage);
1255         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1256         check_added_monitors!(nodes[0], 1);
1257
1258         // Broadcast node 1 commitment txn
1259         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1260
1261         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1262         let mut has_both_htlcs = 0; // check htlcs match ones committed
1263         for outp in remote_txn[0].output.iter() {
1264                 if outp.value == 800_000 / 1000 {
1265                         has_both_htlcs += 1;
1266                 } else if outp.value == 900_000 / 1000 {
1267                         has_both_htlcs += 1;
1268                 }
1269         }
1270         assert_eq!(has_both_htlcs, 2);
1271
1272         mine_transaction(&nodes[0], &remote_txn[0]);
1273         check_added_monitors!(nodes[0], 1);
1274         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1275         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1276
1277         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1278         assert_eq!(claim_txn.len(), 3);
1279
1280         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1281         check_spends!(claim_txn[1], remote_txn[0]);
1282         check_spends!(claim_txn[2], remote_txn[0]);
1283         let preimage_tx = &claim_txn[0];
1284         let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1285                 (&claim_txn[1], &claim_txn[2])
1286         } else {
1287                 (&claim_txn[2], &claim_txn[1])
1288         };
1289
1290         assert_eq!(preimage_tx.input.len(), 1);
1291         assert_eq!(preimage_bump_tx.input.len(), 1);
1292
1293         assert_eq!(preimage_tx.input.len(), 1);
1294         assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1295         assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1296
1297         assert_eq!(timeout_tx.input.len(), 1);
1298         assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1299         check_spends!(timeout_tx, remote_txn[0]);
1300         assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1301
1302         let events = nodes[0].node.get_and_clear_pending_msg_events();
1303         assert_eq!(events.len(), 3);
1304         for e in events {
1305                 match e {
1306                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1307                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1308                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1309                                 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1310                         },
1311                         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, .. } } => {
1312                                 assert!(update_add_htlcs.is_empty());
1313                                 assert!(update_fail_htlcs.is_empty());
1314                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1315                                 assert!(update_fail_malformed_htlcs.is_empty());
1316                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1317                         },
1318                         _ => panic!("Unexpected event"),
1319                 }
1320         }
1321 }
1322
1323 #[test]
1324 fn test_basic_channel_reserve() {
1325         let chanmon_cfgs = create_chanmon_cfgs(2);
1326         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1327         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1328         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1329         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1330
1331         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1332         let channel_reserve = chan_stat.channel_reserve_msat;
1333
1334         // The 2* and +1 are for the fee spike reserve.
1335         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));
1336         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1337         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1338         let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1339         match err {
1340                 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1341                         match &fails[0] {
1342                                 &APIError::ChannelUnavailable{ref err} =>
1343                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1344                                 _ => panic!("Unexpected error variant"),
1345                         }
1346                 },
1347                 _ => panic!("Unexpected error variant"),
1348         }
1349         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1350         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put our balance under counterparty-announced channel reserve value", 1);
1351
1352         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1353 }
1354
1355 #[test]
1356 fn test_fee_spike_violation_fails_htlc() {
1357         let chanmon_cfgs = create_chanmon_cfgs(2);
1358         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1359         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1360         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1361         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1362
1363         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1364         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1365         let secp_ctx = Secp256k1::new();
1366         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1367
1368         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1369
1370         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1371         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1372         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1373         let msg = msgs::UpdateAddHTLC {
1374                 channel_id: chan.2,
1375                 htlc_id: 0,
1376                 amount_msat: htlc_msat,
1377                 payment_hash: payment_hash,
1378                 cltv_expiry: htlc_cltv,
1379                 onion_routing_packet: onion_packet,
1380         };
1381
1382         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1383
1384         // Now manually create the commitment_signed message corresponding to the update_add
1385         // nodes[0] just sent. In the code for construction of this message, "local" refers
1386         // to the sender of the message, and "remote" refers to the receiver.
1387
1388         let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1389
1390         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1391
1392         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1393         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1394         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1395                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1396                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1397                 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1398                 let chan_signer = local_chan.get_signer();
1399                 // Make the signer believe we validated another commitment, so we can release the secret
1400                 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1401
1402                 let pubkeys = chan_signer.pubkeys();
1403                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1404                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1405                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1406                  chan_signer.pubkeys().funding_pubkey)
1407         };
1408         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1409                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1410                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1411                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1412                 let chan_signer = remote_chan.get_signer();
1413                 let pubkeys = chan_signer.pubkeys();
1414                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1415                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1416                  chan_signer.pubkeys().funding_pubkey)
1417         };
1418
1419         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1420         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1421                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1422
1423         // Build the remote commitment transaction so we can sign it, and then later use the
1424         // signature for the commitment_signed message.
1425         let local_chan_balance = 1313;
1426
1427         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1428                 offered: false,
1429                 amount_msat: 3460001,
1430                 cltv_expiry: htlc_cltv,
1431                 payment_hash,
1432                 transaction_output_index: Some(1),
1433         };
1434
1435         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1436
1437         let res = {
1438                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1439                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1440                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
1441                 let local_chan_signer = local_chan.get_signer();
1442                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1443                         commitment_number,
1444                         95000,
1445                         local_chan_balance,
1446                         local_chan.opt_anchors(), local_funding, remote_funding,
1447                         commit_tx_keys.clone(),
1448                         feerate_per_kw,
1449                         &mut vec![(accepted_htlc_info, ())],
1450                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1451                 );
1452                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1453         };
1454
1455         let commit_signed_msg = msgs::CommitmentSigned {
1456                 channel_id: chan.2,
1457                 signature: res.0,
1458                 htlc_signatures: res.1
1459         };
1460
1461         // Send the commitment_signed message to the nodes[1].
1462         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1463         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1464
1465         // Send the RAA to nodes[1].
1466         let raa_msg = msgs::RevokeAndACK {
1467                 channel_id: chan.2,
1468                 per_commitment_secret: local_secret,
1469                 next_per_commitment_point: next_local_point
1470         };
1471         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1472
1473         let events = nodes[1].node.get_and_clear_pending_msg_events();
1474         assert_eq!(events.len(), 1);
1475         // Make sure the HTLC failed in the way we expect.
1476         match events[0] {
1477                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1478                         assert_eq!(update_fail_htlcs.len(), 1);
1479                         update_fail_htlcs[0].clone()
1480                 },
1481                 _ => panic!("Unexpected event"),
1482         };
1483         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1484                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1485
1486         check_added_monitors!(nodes[1], 2);
1487 }
1488
1489 #[test]
1490 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1491         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1492         // Set the fee rate for the channel very high, to the point where the fundee
1493         // sending any above-dust amount would result in a channel reserve violation.
1494         // In this test we check that we would be prevented from sending an HTLC in
1495         // this situation.
1496         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1497         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1498         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1499         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1500         let default_config = UserConfig::default();
1501         let opt_anchors = false;
1502
1503         let mut push_amt = 100_000_000;
1504         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1505
1506         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1507
1508         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1509
1510         // Sending exactly enough to hit the reserve amount should be accepted
1511         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1512                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1513         }
1514
1515         // However one more HTLC should be significantly over the reserve amount and fail.
1516         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1517         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 },
1518                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1519         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1520         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);
1521 }
1522
1523 #[test]
1524 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1525         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1526         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1527         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1528         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1529         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1530         let default_config = UserConfig::default();
1531         let opt_anchors = false;
1532
1533         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1534         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1535         // transaction fee with 0 HTLCs (183 sats)).
1536         let mut push_amt = 100_000_000;
1537         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1538         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1539         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1540
1541         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1542         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1543                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1544         }
1545
1546         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1547         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1548         let secp_ctx = Secp256k1::new();
1549         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1550         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1551         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1552         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1553         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1554         let msg = msgs::UpdateAddHTLC {
1555                 channel_id: chan.2,
1556                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1557                 amount_msat: htlc_msat,
1558                 payment_hash: payment_hash,
1559                 cltv_expiry: htlc_cltv,
1560                 onion_routing_packet: onion_packet,
1561         };
1562
1563         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1564         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1565         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);
1566         assert_eq!(nodes[0].node.list_channels().len(), 0);
1567         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1568         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1569         check_added_monitors!(nodes[0], 1);
1570         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() });
1571 }
1572
1573 #[test]
1574 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1575         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1576         // calculating our commitment transaction fee (this was previously broken).
1577         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1578         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1579
1580         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1581         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1582         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1583         let default_config = UserConfig::default();
1584         let opt_anchors = false;
1585
1586         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1587         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1588         // transaction fee with 0 HTLCs (183 sats)).
1589         let mut push_amt = 100_000_000;
1590         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1591         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1592         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1593
1594         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1595                 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1596         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1597         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1598         // commitment transaction fee.
1599         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1600
1601         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1602         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1603                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1604         }
1605
1606         // One more than the dust amt should fail, however.
1607         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1608         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 },
1609                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1610 }
1611
1612 #[test]
1613 fn test_chan_init_feerate_unaffordability() {
1614         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1615         // channel reserve and feerate requirements.
1616         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1617         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1618         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1619         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1620         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1621         let default_config = UserConfig::default();
1622         let opt_anchors = false;
1623
1624         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1625         // HTLC.
1626         let mut push_amt = 100_000_000;
1627         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1628         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1629                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1630
1631         // During open, we don't have a "counterparty channel reserve" to check against, so that
1632         // requirement only comes into play on the open_channel handling side.
1633         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1634         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1635         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1636         open_channel_msg.push_msat += 1;
1637         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1638
1639         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1640         assert_eq!(msg_events.len(), 1);
1641         match msg_events[0] {
1642                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1643                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1644                 },
1645                 _ => panic!("Unexpected event"),
1646         }
1647 }
1648
1649 #[test]
1650 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1651         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1652         // calculating our counterparty's commitment transaction fee (this was previously broken).
1653         let chanmon_cfgs = create_chanmon_cfgs(2);
1654         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1655         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1656         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1657         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1658
1659         let payment_amt = 46000; // Dust amount
1660         // In the previous code, these first four payments would succeed.
1661         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1662         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1663         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1664         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1665
1666         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1667         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1668         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1669         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1670         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1671         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1672
1673         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1674         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1675         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1676         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1677 }
1678
1679 #[test]
1680 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1681         let chanmon_cfgs = create_chanmon_cfgs(3);
1682         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1683         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1684         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1685         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1686         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1687
1688         let feemsat = 239;
1689         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1690         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1691         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1692         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
1693
1694         // Add a 2* and +1 for the fee spike reserve.
1695         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1696         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;
1697         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1698
1699         // Add a pending HTLC.
1700         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1701         let payment_event_1 = {
1702                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1703                 check_added_monitors!(nodes[0], 1);
1704
1705                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1706                 assert_eq!(events.len(), 1);
1707                 SendEvent::from_event(events.remove(0))
1708         };
1709         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1710
1711         // Attempt to trigger a channel reserve violation --> payment failure.
1712         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1713         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;
1714         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1715         let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1716
1717         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1718         let secp_ctx = Secp256k1::new();
1719         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1720         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1721         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1722         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1723         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1724         let msg = msgs::UpdateAddHTLC {
1725                 channel_id: chan.2,
1726                 htlc_id: 1,
1727                 amount_msat: htlc_msat + 1,
1728                 payment_hash: our_payment_hash_1,
1729                 cltv_expiry: htlc_cltv,
1730                 onion_routing_packet: onion_packet,
1731         };
1732
1733         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1734         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1735         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1736         assert_eq!(nodes[1].node.list_channels().len(), 1);
1737         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1738         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1739         check_added_monitors!(nodes[1], 1);
1740         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1741 }
1742
1743 #[test]
1744 fn test_inbound_outbound_capacity_is_not_zero() {
1745         let chanmon_cfgs = create_chanmon_cfgs(2);
1746         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1747         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1748         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1749         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1750         let channels0 = node_chanmgrs[0].list_channels();
1751         let channels1 = node_chanmgrs[1].list_channels();
1752         let default_config = UserConfig::default();
1753         assert_eq!(channels0.len(), 1);
1754         assert_eq!(channels1.len(), 1);
1755
1756         let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1757         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1758         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1759
1760         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1761         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1762 }
1763
1764 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1765         (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1766 }
1767
1768 #[test]
1769 fn test_channel_reserve_holding_cell_htlcs() {
1770         let chanmon_cfgs = create_chanmon_cfgs(3);
1771         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1772         // When this test was written, the default base fee floated based on the HTLC count.
1773         // It is now fixed, so we simply set the fee to the expected value here.
1774         let mut config = test_default_channel_config();
1775         config.channel_config.forwarding_fee_base_msat = 239;
1776         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1777         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1778         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1779         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1780
1781         let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1782         let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1783
1784         let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1785         let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1786
1787         macro_rules! expect_forward {
1788                 ($node: expr) => {{
1789                         let mut events = $node.node.get_and_clear_pending_msg_events();
1790                         assert_eq!(events.len(), 1);
1791                         check_added_monitors!($node, 1);
1792                         let payment_event = SendEvent::from_event(events.remove(0));
1793                         payment_event
1794                 }}
1795         }
1796
1797         let feemsat = 239; // set above
1798         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1799         let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1800         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_1.2);
1801
1802         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1803
1804         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1805         {
1806                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1807                         .with_features(nodes[2].node.invoice_features()).with_max_channel_saturation_power_of_half(0);
1808                 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);
1809                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1810                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1811
1812                 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 },
1813                         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)));
1814                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1815                 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);
1816         }
1817
1818         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1819         // nodes[0]'s wealth
1820         loop {
1821                 let amt_msat = recv_value_0 + total_fee_msat;
1822                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1823                 // Also, ensure that each payment has enough to be over the dust limit to
1824                 // ensure it'll be included in each commit tx fee calculation.
1825                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1826                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1827                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1828                         break;
1829                 }
1830
1831                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1832                         .with_features(nodes[2].node.invoice_features()).with_max_channel_saturation_power_of_half(0);
1833                 let route = get_route!(nodes[0], payment_params, recv_value_0, TEST_FINAL_CLTV).unwrap();
1834                 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1835                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1836
1837                 let (stat01_, stat11_, stat12_, stat22_) = (
1838                         get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1839                         get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1840                         get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1841                         get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1842                 );
1843
1844                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1845                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1846                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1847                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1848                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1849         }
1850
1851         // adding pending output.
1852         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1853         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1854         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1855         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1856         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1857         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1858         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1859         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1860         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1861         // policy.
1862         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1863         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1864         let amt_msat_1 = recv_value_1 + total_fee_msat;
1865
1866         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);
1867         let payment_event_1 = {
1868                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1869                 check_added_monitors!(nodes[0], 1);
1870
1871                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1872                 assert_eq!(events.len(), 1);
1873                 SendEvent::from_event(events.remove(0))
1874         };
1875         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1876
1877         // channel reserve test with htlc pending output > 0
1878         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1879         {
1880                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1881                 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 },
1882                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1883                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1884         }
1885
1886         // split the rest to test holding cell
1887         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1888         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1889         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1890         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1891         {
1892                 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1893                 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);
1894         }
1895
1896         // now see if they go through on both sides
1897         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);
1898         // but this will stuck in the holding cell
1899         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1900         check_added_monitors!(nodes[0], 0);
1901         let events = nodes[0].node.get_and_clear_pending_events();
1902         assert_eq!(events.len(), 0);
1903
1904         // test with outbound holding cell amount > 0
1905         {
1906                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1907                 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 },
1908                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1909                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1910                 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put our balance under counterparty-announced channel reserve value", 2);
1911         }
1912
1913         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);
1914         // this will also stuck in the holding cell
1915         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1916         check_added_monitors!(nodes[0], 0);
1917         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1918         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1919
1920         // flush the pending htlc
1921         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1922         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1923         check_added_monitors!(nodes[1], 1);
1924
1925         // the pending htlc should be promoted to committed
1926         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1927         check_added_monitors!(nodes[0], 1);
1928         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1929
1930         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1931         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1932         // No commitment_signed so get_event_msg's assert(len == 1) passes
1933         check_added_monitors!(nodes[0], 1);
1934
1935         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1936         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1937         check_added_monitors!(nodes[1], 1);
1938
1939         expect_pending_htlcs_forwardable!(nodes[1]);
1940
1941         let ref payment_event_11 = expect_forward!(nodes[1]);
1942         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1943         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1944
1945         expect_pending_htlcs_forwardable!(nodes[2]);
1946         expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1947
1948         // flush the htlcs in the holding cell
1949         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1950         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1951         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1952         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1953         expect_pending_htlcs_forwardable!(nodes[1]);
1954
1955         let ref payment_event_3 = expect_forward!(nodes[1]);
1956         assert_eq!(payment_event_3.msgs.len(), 2);
1957         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1958         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1959
1960         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1961         expect_pending_htlcs_forwardable!(nodes[2]);
1962
1963         let events = nodes[2].node.get_and_clear_pending_events();
1964         assert_eq!(events.len(), 2);
1965         match events[0] {
1966                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
1967                         assert_eq!(our_payment_hash_21, *payment_hash);
1968                         assert_eq!(recv_value_21, amount_msat);
1969                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
1970                         assert_eq!(via_channel_id, Some(chan_2.2));
1971                         match &purpose {
1972                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1973                                         assert!(payment_preimage.is_none());
1974                                         assert_eq!(our_payment_secret_21, *payment_secret);
1975                                 },
1976                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1977                         }
1978                 },
1979                 _ => panic!("Unexpected event"),
1980         }
1981         match events[1] {
1982                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
1983                         assert_eq!(our_payment_hash_22, *payment_hash);
1984                         assert_eq!(recv_value_22, amount_msat);
1985                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
1986                         assert_eq!(via_channel_id, Some(chan_2.2));
1987                         match &purpose {
1988                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1989                                         assert!(payment_preimage.is_none());
1990                                         assert_eq!(our_payment_secret_22, *payment_secret);
1991                                 },
1992                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1993                         }
1994                 },
1995                 _ => panic!("Unexpected event"),
1996         }
1997
1998         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1999         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2000         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2001
2002         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2003         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2004         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2005
2006         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2007         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);
2008         let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2009         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2010         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2011
2012         let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2013         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2014 }
2015
2016 #[test]
2017 fn channel_reserve_in_flight_removes() {
2018         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2019         // can send to its counterparty, but due to update ordering, the other side may not yet have
2020         // considered those HTLCs fully removed.
2021         // This tests that we don't count HTLCs which will not be included in the next remote
2022         // commitment transaction towards the reserve value (as it implies no commitment transaction
2023         // will be generated which violates the remote reserve value).
2024         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2025         // To test this we:
2026         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2027         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2028         //    you only consider the value of the first HTLC, it may not),
2029         //  * start routing a third HTLC from A to B,
2030         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2031         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2032         //  * deliver the first fulfill from B
2033         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2034         //    claim,
2035         //  * deliver A's response CS and RAA.
2036         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2037         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2038         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2039         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2040         let chanmon_cfgs = create_chanmon_cfgs(2);
2041         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2042         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2043         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2044         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2045
2046         let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2047         // Route the first two HTLCs.
2048         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2049         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2050         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2051
2052         // Start routing the third HTLC (this is just used to get everyone in the right state).
2053         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2054         let send_1 = {
2055                 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2056                 check_added_monitors!(nodes[0], 1);
2057                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2058                 assert_eq!(events.len(), 1);
2059                 SendEvent::from_event(events.remove(0))
2060         };
2061
2062         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2063         // initial fulfill/CS.
2064         nodes[1].node.claim_funds(payment_preimage_1);
2065         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2066         check_added_monitors!(nodes[1], 1);
2067         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2068
2069         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2070         // remove the second HTLC when we send the HTLC back from B to A.
2071         nodes[1].node.claim_funds(payment_preimage_2);
2072         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2073         check_added_monitors!(nodes[1], 1);
2074         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2075
2076         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2077         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2078         check_added_monitors!(nodes[0], 1);
2079         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2080         expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2081
2082         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2083         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2084         check_added_monitors!(nodes[1], 1);
2085         // B is already AwaitingRAA, so cant generate a CS here
2086         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2087
2088         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2089         check_added_monitors!(nodes[1], 1);
2090         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2091
2092         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2093         check_added_monitors!(nodes[0], 1);
2094         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2095
2096         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2097         check_added_monitors!(nodes[1], 1);
2098         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2099
2100         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2101         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2102         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2103         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2104         // on-chain as necessary).
2105         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2106         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2107         check_added_monitors!(nodes[0], 1);
2108         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2109         expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2110
2111         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2112         check_added_monitors!(nodes[1], 1);
2113         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2114
2115         expect_pending_htlcs_forwardable!(nodes[1]);
2116         expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2117
2118         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2119         // resolve the second HTLC from A's point of view.
2120         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2121         check_added_monitors!(nodes[0], 1);
2122         expect_payment_path_successful!(nodes[0]);
2123         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2124
2125         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2126         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2127         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2128         let send_2 = {
2129                 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2130                 check_added_monitors!(nodes[1], 1);
2131                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2132                 assert_eq!(events.len(), 1);
2133                 SendEvent::from_event(events.remove(0))
2134         };
2135
2136         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2137         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2138         check_added_monitors!(nodes[0], 1);
2139         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2140
2141         // Now just resolve all the outstanding messages/HTLCs for completeness...
2142
2143         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2144         check_added_monitors!(nodes[1], 1);
2145         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2146
2147         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2148         check_added_monitors!(nodes[1], 1);
2149
2150         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2151         check_added_monitors!(nodes[0], 1);
2152         expect_payment_path_successful!(nodes[0]);
2153         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2154
2155         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2156         check_added_monitors!(nodes[1], 1);
2157         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2158
2159         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2160         check_added_monitors!(nodes[0], 1);
2161
2162         expect_pending_htlcs_forwardable!(nodes[0]);
2163         expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2164
2165         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2166         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2167 }
2168
2169 #[test]
2170 fn channel_monitor_network_test() {
2171         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2172         // tests that ChannelMonitor is able to recover from various states.
2173         let chanmon_cfgs = create_chanmon_cfgs(5);
2174         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2175         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2176         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2177
2178         // Create some initial channels
2179         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2180         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2181         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2182         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2183
2184         // Make sure all nodes are at the same starting height
2185         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2186         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2187         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2188         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2189         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2190
2191         // Rebalance the network a bit by relaying one payment through all the channels...
2192         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2193         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2194         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2195         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2196
2197         // Simple case with no pending HTLCs:
2198         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2199         check_added_monitors!(nodes[1], 1);
2200         check_closed_broadcast!(nodes[1], true);
2201         {
2202                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2203                 assert_eq!(node_txn.len(), 1);
2204                 mine_transaction(&nodes[0], &node_txn[0]);
2205                 check_added_monitors!(nodes[0], 1);
2206                 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2207         }
2208         check_closed_broadcast!(nodes[0], true);
2209         assert_eq!(nodes[0].node.list_channels().len(), 0);
2210         assert_eq!(nodes[1].node.list_channels().len(), 1);
2211         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2212         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2213
2214         // One pending HTLC is discarded by the force-close:
2215         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2216
2217         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2218         // broadcasted until we reach the timelock time).
2219         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2220         check_closed_broadcast!(nodes[1], true);
2221         check_added_monitors!(nodes[1], 1);
2222         {
2223                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2224                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2225                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2226                 mine_transaction(&nodes[2], &node_txn[0]);
2227                 check_added_monitors!(nodes[2], 1);
2228                 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2229         }
2230         check_closed_broadcast!(nodes[2], true);
2231         assert_eq!(nodes[1].node.list_channels().len(), 0);
2232         assert_eq!(nodes[2].node.list_channels().len(), 1);
2233         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2234         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2235
2236         macro_rules! claim_funds {
2237                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2238                         {
2239                                 $node.node.claim_funds($preimage);
2240                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2241                                 check_added_monitors!($node, 1);
2242
2243                                 let events = $node.node.get_and_clear_pending_msg_events();
2244                                 assert_eq!(events.len(), 1);
2245                                 match events[0] {
2246                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2247                                                 assert!(update_add_htlcs.is_empty());
2248                                                 assert!(update_fail_htlcs.is_empty());
2249                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2250                                         },
2251                                         _ => panic!("Unexpected event"),
2252                                 };
2253                         }
2254                 }
2255         }
2256
2257         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2258         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2259         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2260         check_added_monitors!(nodes[2], 1);
2261         check_closed_broadcast!(nodes[2], true);
2262         let node2_commitment_txid;
2263         {
2264                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2265                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2266                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2267                 node2_commitment_txid = node_txn[0].txid();
2268
2269                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2270                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2271                 mine_transaction(&nodes[3], &node_txn[0]);
2272                 check_added_monitors!(nodes[3], 1);
2273                 check_preimage_claim(&nodes[3], &node_txn);
2274         }
2275         check_closed_broadcast!(nodes[3], true);
2276         assert_eq!(nodes[2].node.list_channels().len(), 0);
2277         assert_eq!(nodes[3].node.list_channels().len(), 1);
2278         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2279         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2280
2281         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2282         // confusing us in the following tests.
2283         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2284
2285         // One pending HTLC to time out:
2286         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2287         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2288         // buffer space).
2289
2290         let (close_chan_update_1, close_chan_update_2) = {
2291                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2292                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2293                 assert_eq!(events.len(), 2);
2294                 let close_chan_update_1 = match events[0] {
2295                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2296                                 msg.clone()
2297                         },
2298                         _ => panic!("Unexpected event"),
2299                 };
2300                 match events[1] {
2301                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2302                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2303                         },
2304                         _ => panic!("Unexpected event"),
2305                 }
2306                 check_added_monitors!(nodes[3], 1);
2307
2308                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2309                 {
2310                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2311                         node_txn.retain(|tx| {
2312                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2313                                         false
2314                                 } else { true }
2315                         });
2316                 }
2317
2318                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2319
2320                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2321                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2322
2323                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2324                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2325                 assert_eq!(events.len(), 2);
2326                 let close_chan_update_2 = match events[0] {
2327                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2328                                 msg.clone()
2329                         },
2330                         _ => panic!("Unexpected event"),
2331                 };
2332                 match events[1] {
2333                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2334                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2335                         },
2336                         _ => panic!("Unexpected event"),
2337                 }
2338                 check_added_monitors!(nodes[4], 1);
2339                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2340
2341                 mine_transaction(&nodes[4], &node_txn[0]);
2342                 check_preimage_claim(&nodes[4], &node_txn);
2343                 (close_chan_update_1, close_chan_update_2)
2344         };
2345         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2346         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2347         assert_eq!(nodes[3].node.list_channels().len(), 0);
2348         assert_eq!(nodes[4].node.list_channels().len(), 0);
2349
2350         assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2351                 ChannelMonitorUpdateStatus::Completed);
2352         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2353         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2354 }
2355
2356 #[test]
2357 fn test_justice_tx() {
2358         // Test justice txn built on revoked HTLC-Success tx, against both sides
2359         let mut alice_config = UserConfig::default();
2360         alice_config.channel_handshake_config.announced_channel = true;
2361         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2362         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2363         let mut bob_config = UserConfig::default();
2364         bob_config.channel_handshake_config.announced_channel = true;
2365         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2366         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2367         let user_cfgs = [Some(alice_config), Some(bob_config)];
2368         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2369         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2370         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2371         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2372         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2373         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2374         *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2375         // Create some new channels:
2376         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2377
2378         // A pending HTLC which will be revoked:
2379         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2380         // Get the will-be-revoked local txn from nodes[0]
2381         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2382         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2383         assert_eq!(revoked_local_txn[0].input.len(), 1);
2384         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2385         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2386         assert_eq!(revoked_local_txn[1].input.len(), 1);
2387         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2388         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2389         // Revoke the old state
2390         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2391
2392         {
2393                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2394                 {
2395                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2396                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2397                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2398
2399                         check_spends!(node_txn[0], revoked_local_txn[0]);
2400                         node_txn.swap_remove(0);
2401                 }
2402                 check_added_monitors!(nodes[1], 1);
2403                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2404                 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2405
2406                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2407                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2408                 // Verify broadcast of revoked HTLC-timeout
2409                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2410                 check_added_monitors!(nodes[0], 1);
2411                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2412                 // Broadcast revoked HTLC-timeout on node 1
2413                 mine_transaction(&nodes[1], &node_txn[1]);
2414                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2415         }
2416         get_announce_close_broadcast_events(&nodes, 0, 1);
2417
2418         assert_eq!(nodes[0].node.list_channels().len(), 0);
2419         assert_eq!(nodes[1].node.list_channels().len(), 0);
2420
2421         // We test justice_tx build by A on B's revoked HTLC-Success tx
2422         // Create some new channels:
2423         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2424         {
2425                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2426                 node_txn.clear();
2427         }
2428
2429         // A pending HTLC which will be revoked:
2430         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2431         // Get the will-be-revoked local txn from B
2432         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2433         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2434         assert_eq!(revoked_local_txn[0].input.len(), 1);
2435         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2436         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2437         // Revoke the old state
2438         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2439         {
2440                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2441                 {
2442                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2443                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2444                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2445
2446                         check_spends!(node_txn[0], revoked_local_txn[0]);
2447                         node_txn.swap_remove(0);
2448                 }
2449                 check_added_monitors!(nodes[0], 1);
2450                 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2451
2452                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2453                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2454                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2455                 check_added_monitors!(nodes[1], 1);
2456                 mine_transaction(&nodes[0], &node_txn[1]);
2457                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2458                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2459         }
2460         get_announce_close_broadcast_events(&nodes, 0, 1);
2461         assert_eq!(nodes[0].node.list_channels().len(), 0);
2462         assert_eq!(nodes[1].node.list_channels().len(), 0);
2463 }
2464
2465 #[test]
2466 fn revoked_output_claim() {
2467         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2468         // transaction is broadcast by its counterparty
2469         let chanmon_cfgs = create_chanmon_cfgs(2);
2470         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2471         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2472         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2473         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2474         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2475         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2476         assert_eq!(revoked_local_txn.len(), 1);
2477         // Only output is the full channel value back to nodes[0]:
2478         assert_eq!(revoked_local_txn[0].output.len(), 1);
2479         // Send a payment through, updating everyone's latest commitment txn
2480         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2481
2482         // Inform nodes[1] that nodes[0] broadcast a stale tx
2483         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2484         check_added_monitors!(nodes[1], 1);
2485         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2486         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2487         assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2488
2489         check_spends!(node_txn[0], revoked_local_txn[0]);
2490
2491         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2492         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2493         get_announce_close_broadcast_events(&nodes, 0, 1);
2494         check_added_monitors!(nodes[0], 1);
2495         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2496 }
2497
2498 #[test]
2499 fn claim_htlc_outputs_shared_tx() {
2500         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2501         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2502         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2503         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2504         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2505         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2506
2507         // Create some new channel:
2508         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2509
2510         // Rebalance the network to generate htlc in the two directions
2511         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2512         // 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
2513         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2514         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2515
2516         // Get the will-be-revoked local txn from node[0]
2517         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2518         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2519         assert_eq!(revoked_local_txn[0].input.len(), 1);
2520         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2521         assert_eq!(revoked_local_txn[1].input.len(), 1);
2522         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2523         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2524         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2525
2526         //Revoke the old state
2527         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2528
2529         {
2530                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2531                 check_added_monitors!(nodes[0], 1);
2532                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2533                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2534                 check_added_monitors!(nodes[1], 1);
2535                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2536                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2537                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2538
2539                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2540                 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2541
2542                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2543                 check_spends!(node_txn[0], revoked_local_txn[0]);
2544
2545                 let mut witness_lens = BTreeSet::new();
2546                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2547                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2548                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2549                 assert_eq!(witness_lens.len(), 3);
2550                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2551                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2552                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2553
2554                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2555                 // ANTI_REORG_DELAY confirmations.
2556                 mine_transaction(&nodes[1], &node_txn[0]);
2557                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2558                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2559         }
2560         get_announce_close_broadcast_events(&nodes, 0, 1);
2561         assert_eq!(nodes[0].node.list_channels().len(), 0);
2562         assert_eq!(nodes[1].node.list_channels().len(), 0);
2563 }
2564
2565 #[test]
2566 fn claim_htlc_outputs_single_tx() {
2567         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2568         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2569         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2570         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2571         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2572         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2573
2574         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2575
2576         // Rebalance the network to generate htlc in the two directions
2577         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2578         // 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
2579         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2580         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2581         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2582
2583         // Get the will-be-revoked local txn from node[0]
2584         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2585
2586         //Revoke the old state
2587         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2588
2589         {
2590                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2591                 check_added_monitors!(nodes[0], 1);
2592                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2593                 check_added_monitors!(nodes[1], 1);
2594                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2595                 let mut events = nodes[0].node.get_and_clear_pending_events();
2596                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2597                 match events.last().unwrap() {
2598                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2599                         _ => panic!("Unexpected event"),
2600                 }
2601
2602                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2603                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2604
2605                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2606                 assert_eq!(node_txn.len(), 7);
2607
2608                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2609                 assert_eq!(node_txn[0].input.len(), 1);
2610                 check_spends!(node_txn[0], chan_1.3);
2611                 assert_eq!(node_txn[1].input.len(), 1);
2612                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2613                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2614                 check_spends!(node_txn[1], node_txn[0]);
2615
2616                 // Justice transactions are indices 2-3-4
2617                 assert_eq!(node_txn[2].input.len(), 1);
2618                 assert_eq!(node_txn[3].input.len(), 1);
2619                 assert_eq!(node_txn[4].input.len(), 1);
2620
2621                 check_spends!(node_txn[2], revoked_local_txn[0]);
2622                 check_spends!(node_txn[3], revoked_local_txn[0]);
2623                 check_spends!(node_txn[4], revoked_local_txn[0]);
2624
2625                 let mut witness_lens = BTreeSet::new();
2626                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2627                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2628                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2629                 assert_eq!(witness_lens.len(), 3);
2630                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2631                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2632                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2633
2634                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2635                 // ANTI_REORG_DELAY confirmations.
2636                 mine_transaction(&nodes[1], &node_txn[2]);
2637                 mine_transaction(&nodes[1], &node_txn[3]);
2638                 mine_transaction(&nodes[1], &node_txn[4]);
2639                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2640                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2641         }
2642         get_announce_close_broadcast_events(&nodes, 0, 1);
2643         assert_eq!(nodes[0].node.list_channels().len(), 0);
2644         assert_eq!(nodes[1].node.list_channels().len(), 0);
2645 }
2646
2647 #[test]
2648 fn test_htlc_on_chain_success() {
2649         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2650         // the preimage backward accordingly. So here we test that ChannelManager is
2651         // broadcasting the right event to other nodes in payment path.
2652         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2653         // A --------------------> B ----------------------> C (preimage)
2654         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2655         // commitment transaction was broadcast.
2656         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2657         // towards B.
2658         // B should be able to claim via preimage if A then broadcasts its local tx.
2659         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2660         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2661         // PaymentSent event).
2662
2663         let chanmon_cfgs = create_chanmon_cfgs(3);
2664         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2665         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2666         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2667
2668         // Create some initial channels
2669         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2670         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2671
2672         // Ensure all nodes are at the same height
2673         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2674         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2675         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2676         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2677
2678         // Rebalance the network a bit by relaying one payment through all the channels...
2679         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2680         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2681
2682         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2683         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2684
2685         // Broadcast legit commitment tx from C on B's chain
2686         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2687         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2688         assert_eq!(commitment_tx.len(), 1);
2689         check_spends!(commitment_tx[0], chan_2.3);
2690         nodes[2].node.claim_funds(our_payment_preimage);
2691         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2692         nodes[2].node.claim_funds(our_payment_preimage_2);
2693         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2694         check_added_monitors!(nodes[2], 2);
2695         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2696         assert!(updates.update_add_htlcs.is_empty());
2697         assert!(updates.update_fail_htlcs.is_empty());
2698         assert!(updates.update_fail_malformed_htlcs.is_empty());
2699         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2700
2701         mine_transaction(&nodes[2], &commitment_tx[0]);
2702         check_closed_broadcast!(nodes[2], true);
2703         check_added_monitors!(nodes[2], 1);
2704         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2705         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2706         assert_eq!(node_txn.len(), 2);
2707         check_spends!(node_txn[0], commitment_tx[0]);
2708         check_spends!(node_txn[1], commitment_tx[0]);
2709         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2710         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2711         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2712         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2713         assert_eq!(node_txn[0].lock_time.0, 0);
2714         assert_eq!(node_txn[1].lock_time.0, 0);
2715
2716         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2717         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2718         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone(), node_txn[1].clone()]});
2719         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2720         {
2721                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2722                 assert_eq!(added_monitors.len(), 1);
2723                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2724                 added_monitors.clear();
2725         }
2726         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2727         assert_eq!(forwarded_events.len(), 3);
2728         match forwarded_events[0] {
2729                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2730                 _ => panic!("Unexpected event"),
2731         }
2732         let chan_id = Some(chan_1.2);
2733         match forwarded_events[1] {
2734                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2735                         assert_eq!(fee_earned_msat, Some(1000));
2736                         assert_eq!(prev_channel_id, chan_id);
2737                         assert_eq!(claim_from_onchain_tx, true);
2738                         assert_eq!(next_channel_id, Some(chan_2.2));
2739                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2740                 },
2741                 _ => panic!()
2742         }
2743         match forwarded_events[2] {
2744                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2745                         assert_eq!(fee_earned_msat, Some(1000));
2746                         assert_eq!(prev_channel_id, chan_id);
2747                         assert_eq!(claim_from_onchain_tx, true);
2748                         assert_eq!(next_channel_id, Some(chan_2.2));
2749                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2750                 },
2751                 _ => panic!()
2752         }
2753         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2754         {
2755                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2756                 assert_eq!(added_monitors.len(), 2);
2757                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2758                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2759                 added_monitors.clear();
2760         }
2761         assert_eq!(events.len(), 3);
2762
2763         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2764         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2765
2766         match nodes_2_event {
2767                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2768                 _ => panic!("Unexpected event"),
2769         }
2770
2771         match nodes_0_event {
2772                 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, .. } } => {
2773                         assert!(update_add_htlcs.is_empty());
2774                         assert!(update_fail_htlcs.is_empty());
2775                         assert_eq!(update_fulfill_htlcs.len(), 1);
2776                         assert!(update_fail_malformed_htlcs.is_empty());
2777                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2778                 },
2779                 _ => panic!("Unexpected event"),
2780         };
2781
2782         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2783         match events[0] {
2784                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2785                 _ => panic!("Unexpected event"),
2786         }
2787
2788         macro_rules! check_tx_local_broadcast {
2789                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2790                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2791                         assert_eq!(node_txn.len(), 2);
2792                         // Node[1]: 2 * HTLC-timeout tx
2793                         // Node[0]: 2 * HTLC-timeout tx
2794                         check_spends!(node_txn[0], $commitment_tx);
2795                         check_spends!(node_txn[1], $commitment_tx);
2796                         assert_ne!(node_txn[0].lock_time.0, 0);
2797                         assert_ne!(node_txn[1].lock_time.0, 0);
2798                         if $htlc_offered {
2799                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2800                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2801                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2802                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2803                         } else {
2804                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2805                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2806                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2807                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2808                         }
2809                         node_txn.clear();
2810                 } }
2811         }
2812         // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2813         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2814
2815         // Broadcast legit commitment tx from A on B's chain
2816         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2817         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2818         check_spends!(node_a_commitment_tx[0], chan_1.3);
2819         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2820         check_closed_broadcast!(nodes[1], true);
2821         check_added_monitors!(nodes[1], 1);
2822         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2823         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2824         assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2825         let commitment_spend =
2826                 if node_txn.len() == 1 {
2827                         &node_txn[0]
2828                 } else {
2829                         // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2830                         // FullBlockViaListen
2831                         if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2832                                 check_spends!(node_txn[1], commitment_tx[0]);
2833                                 check_spends!(node_txn[2], commitment_tx[0]);
2834                                 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2835                                 &node_txn[0]
2836                         } else {
2837                                 check_spends!(node_txn[0], commitment_tx[0]);
2838                                 check_spends!(node_txn[1], commitment_tx[0]);
2839                                 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2840                                 &node_txn[2]
2841                         }
2842                 };
2843
2844         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2845         assert_eq!(commitment_spend.input.len(), 2);
2846         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2847         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2848         assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1 + 1);
2849         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2850         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2851         // we already checked the same situation with A.
2852
2853         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2854         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2855         connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2856         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2857         check_closed_broadcast!(nodes[0], true);
2858         check_added_monitors!(nodes[0], 1);
2859         let events = nodes[0].node.get_and_clear_pending_events();
2860         assert_eq!(events.len(), 5);
2861         let mut first_claimed = false;
2862         for event in events {
2863                 match event {
2864                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2865                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2866                                         assert!(!first_claimed);
2867                                         first_claimed = true;
2868                                 } else {
2869                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2870                                         assert_eq!(payment_hash, payment_hash_2);
2871                                 }
2872                         },
2873                         Event::PaymentPathSuccessful { .. } => {},
2874                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2875                         _ => panic!("Unexpected event"),
2876                 }
2877         }
2878         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
2879 }
2880
2881 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2882         // Test that in case of a unilateral close onchain, we detect the state of output and
2883         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2884         // broadcasting the right event to other nodes in payment path.
2885         // A ------------------> B ----------------------> C (timeout)
2886         //    B's commitment tx                 C's commitment tx
2887         //            \                                  \
2888         //         B's HTLC timeout tx               B's timeout tx
2889
2890         let chanmon_cfgs = create_chanmon_cfgs(3);
2891         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2892         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2893         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2894         *nodes[0].connect_style.borrow_mut() = connect_style;
2895         *nodes[1].connect_style.borrow_mut() = connect_style;
2896         *nodes[2].connect_style.borrow_mut() = connect_style;
2897
2898         // Create some intial channels
2899         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2900         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2901
2902         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2903         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2904         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2905
2906         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2907
2908         // Broadcast legit commitment tx from C on B's chain
2909         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2910         check_spends!(commitment_tx[0], chan_2.3);
2911         nodes[2].node.fail_htlc_backwards(&payment_hash);
2912         check_added_monitors!(nodes[2], 0);
2913         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2914         check_added_monitors!(nodes[2], 1);
2915
2916         let events = nodes[2].node.get_and_clear_pending_msg_events();
2917         assert_eq!(events.len(), 1);
2918         match events[0] {
2919                 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, .. } } => {
2920                         assert!(update_add_htlcs.is_empty());
2921                         assert!(!update_fail_htlcs.is_empty());
2922                         assert!(update_fulfill_htlcs.is_empty());
2923                         assert!(update_fail_malformed_htlcs.is_empty());
2924                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2925                 },
2926                 _ => panic!("Unexpected event"),
2927         };
2928         mine_transaction(&nodes[2], &commitment_tx[0]);
2929         check_closed_broadcast!(nodes[2], true);
2930         check_added_monitors!(nodes[2], 1);
2931         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2932         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2933         assert_eq!(node_txn.len(), 0);
2934
2935         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2936         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2937         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2938         mine_transaction(&nodes[1], &commitment_tx[0]);
2939         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2940         let timeout_tx;
2941         {
2942                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2943                 assert_eq!(node_txn.len(), 3); // 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2944
2945                 check_spends!(node_txn[2], commitment_tx[0]);
2946                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2947
2948                 check_spends!(node_txn[0], chan_2.3);
2949                 check_spends!(node_txn[1], node_txn[0]);
2950                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2951                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2952
2953                 timeout_tx = node_txn[2].clone();
2954                 node_txn.clear();
2955         }
2956
2957         mine_transaction(&nodes[1], &timeout_tx);
2958         check_added_monitors!(nodes[1], 1);
2959         check_closed_broadcast!(nodes[1], true);
2960
2961         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2962
2963         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 }]);
2964         check_added_monitors!(nodes[1], 1);
2965         let events = nodes[1].node.get_and_clear_pending_msg_events();
2966         assert_eq!(events.len(), 1);
2967         match events[0] {
2968                 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, .. } } => {
2969                         assert!(update_add_htlcs.is_empty());
2970                         assert!(!update_fail_htlcs.is_empty());
2971                         assert!(update_fulfill_htlcs.is_empty());
2972                         assert!(update_fail_malformed_htlcs.is_empty());
2973                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2974                 },
2975                 _ => panic!("Unexpected event"),
2976         };
2977
2978         // Broadcast legit commitment tx from B on A's chain
2979         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2980         check_spends!(commitment_tx[0], chan_1.3);
2981
2982         mine_transaction(&nodes[0], &commitment_tx[0]);
2983         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2984
2985         check_closed_broadcast!(nodes[0], true);
2986         check_added_monitors!(nodes[0], 1);
2987         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2988         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
2989         assert_eq!(node_txn.len(), 1);
2990         check_spends!(node_txn[0], commitment_tx[0]);
2991         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2992 }
2993
2994 #[test]
2995 fn test_htlc_on_chain_timeout() {
2996         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
2997         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
2998         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
2999 }
3000
3001 #[test]
3002 fn test_simple_commitment_revoked_fail_backward() {
3003         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3004         // and fail backward accordingly.
3005
3006         let chanmon_cfgs = create_chanmon_cfgs(3);
3007         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3008         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3009         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3010
3011         // Create some initial channels
3012         create_announced_chan_between_nodes(&nodes, 0, 1);
3013         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3014
3015         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3016         // Get the will-be-revoked local txn from nodes[2]
3017         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3018         // Revoke the old state
3019         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3020
3021         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3022
3023         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3024         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3025         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3026         check_added_monitors!(nodes[1], 1);
3027         check_closed_broadcast!(nodes[1], true);
3028
3029         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 }]);
3030         check_added_monitors!(nodes[1], 1);
3031         let events = nodes[1].node.get_and_clear_pending_msg_events();
3032         assert_eq!(events.len(), 1);
3033         match events[0] {
3034                 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, .. } } => {
3035                         assert!(update_add_htlcs.is_empty());
3036                         assert_eq!(update_fail_htlcs.len(), 1);
3037                         assert!(update_fulfill_htlcs.is_empty());
3038                         assert!(update_fail_malformed_htlcs.is_empty());
3039                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3040
3041                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3042                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3043                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3044                 },
3045                 _ => panic!("Unexpected event"),
3046         }
3047 }
3048
3049 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3050         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3051         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3052         // commitment transaction anymore.
3053         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3054         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3055         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3056         // technically disallowed and we should probably handle it reasonably.
3057         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3058         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3059         // transactions:
3060         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3061         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3062         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3063         //   and once they revoke the previous commitment transaction (allowing us to send a new
3064         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3065         let chanmon_cfgs = create_chanmon_cfgs(3);
3066         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3067         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3068         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3069
3070         // Create some initial channels
3071         create_announced_chan_between_nodes(&nodes, 0, 1);
3072         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3073
3074         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 });
3075         // Get the will-be-revoked local txn from nodes[2]
3076         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3077         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3078         // Revoke the old state
3079         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3080
3081         let value = if use_dust {
3082                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3083                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3084                 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3085                         .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3086         } else { 3000000 };
3087
3088         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3089         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3090         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3091
3092         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3093         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3094         check_added_monitors!(nodes[2], 1);
3095         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3096         assert!(updates.update_add_htlcs.is_empty());
3097         assert!(updates.update_fulfill_htlcs.is_empty());
3098         assert!(updates.update_fail_malformed_htlcs.is_empty());
3099         assert_eq!(updates.update_fail_htlcs.len(), 1);
3100         assert!(updates.update_fee.is_none());
3101         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3102         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3103         // Drop the last RAA from 3 -> 2
3104
3105         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3106         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3107         check_added_monitors!(nodes[2], 1);
3108         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3109         assert!(updates.update_add_htlcs.is_empty());
3110         assert!(updates.update_fulfill_htlcs.is_empty());
3111         assert!(updates.update_fail_malformed_htlcs.is_empty());
3112         assert_eq!(updates.update_fail_htlcs.len(), 1);
3113         assert!(updates.update_fee.is_none());
3114         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3115         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3116         check_added_monitors!(nodes[1], 1);
3117         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3118         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3119         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3120         check_added_monitors!(nodes[2], 1);
3121
3122         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3123         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3124         check_added_monitors!(nodes[2], 1);
3125         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3126         assert!(updates.update_add_htlcs.is_empty());
3127         assert!(updates.update_fulfill_htlcs.is_empty());
3128         assert!(updates.update_fail_malformed_htlcs.is_empty());
3129         assert_eq!(updates.update_fail_htlcs.len(), 1);
3130         assert!(updates.update_fee.is_none());
3131         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3132         // At this point first_payment_hash has dropped out of the latest two commitment
3133         // transactions that nodes[1] is tracking...
3134         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3135         check_added_monitors!(nodes[1], 1);
3136         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3137         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3138         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3139         check_added_monitors!(nodes[2], 1);
3140
3141         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3142         // on nodes[2]'s RAA.
3143         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3144         nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3145         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3146         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3147         check_added_monitors!(nodes[1], 0);
3148
3149         if deliver_bs_raa {
3150                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3151                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3152                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3153                 check_added_monitors!(nodes[1], 1);
3154                 let events = nodes[1].node.get_and_clear_pending_events();
3155                 assert_eq!(events.len(), 2);
3156                 match events[0] {
3157                         Event::PendingHTLCsForwardable { .. } => { },
3158                         _ => panic!("Unexpected event"),
3159                 };
3160                 match events[1] {
3161                         Event::HTLCHandlingFailed { .. } => { },
3162                         _ => panic!("Unexpected event"),
3163                 }
3164                 // Deliberately don't process the pending fail-back so they all fail back at once after
3165                 // block connection just like the !deliver_bs_raa case
3166         }
3167
3168         let mut failed_htlcs = HashSet::new();
3169         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3170
3171         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3172         check_added_monitors!(nodes[1], 1);
3173         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3174
3175         let events = nodes[1].node.get_and_clear_pending_events();
3176         assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3177         match events[0] {
3178                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3179                 _ => panic!("Unexepected event"),
3180         }
3181         match events[1] {
3182                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3183                         assert_eq!(*payment_hash, fourth_payment_hash);
3184                 },
3185                 _ => panic!("Unexpected event"),
3186         }
3187         match events[2] {
3188                 Event::PaymentFailed { ref payment_hash, .. } => {
3189                         assert_eq!(*payment_hash, fourth_payment_hash);
3190                 },
3191                 _ => panic!("Unexpected event"),
3192         }
3193
3194         nodes[1].node.process_pending_htlc_forwards();
3195         check_added_monitors!(nodes[1], 1);
3196
3197         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3198         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3199
3200         if deliver_bs_raa {
3201                 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3202                 match nodes_2_event {
3203                         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, .. } } => {
3204                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3205                                 assert_eq!(update_add_htlcs.len(), 1);
3206                                 assert!(update_fulfill_htlcs.is_empty());
3207                                 assert!(update_fail_htlcs.is_empty());
3208                                 assert!(update_fail_malformed_htlcs.is_empty());
3209                         },
3210                         _ => panic!("Unexpected event"),
3211                 }
3212         }
3213
3214         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3215         match nodes_2_event {
3216                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3217                         assert_eq!(channel_id, chan_2.2);
3218                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3219                 },
3220                 _ => panic!("Unexpected event"),
3221         }
3222
3223         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3224         match nodes_0_event {
3225                 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, .. } } => {
3226                         assert!(update_add_htlcs.is_empty());
3227                         assert_eq!(update_fail_htlcs.len(), 3);
3228                         assert!(update_fulfill_htlcs.is_empty());
3229                         assert!(update_fail_malformed_htlcs.is_empty());
3230                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3231
3232                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3233                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3234                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3235
3236                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3237
3238                         let events = nodes[0].node.get_and_clear_pending_events();
3239                         assert_eq!(events.len(), 6);
3240                         match events[0] {
3241                                 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3242                                         assert!(failed_htlcs.insert(payment_hash.0));
3243                                         // If we delivered B's RAA we got an unknown preimage error, not something
3244                                         // that we should update our routing table for.
3245                                         if !deliver_bs_raa {
3246                                                 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3247                                         }
3248                                 },
3249                                 _ => panic!("Unexpected event"),
3250                         }
3251                         match events[1] {
3252                                 Event::PaymentFailed { ref payment_hash, .. } => {
3253                                         assert_eq!(*payment_hash, first_payment_hash);
3254                                 },
3255                                 _ => panic!("Unexpected event"),
3256                         }
3257                         match events[2] {
3258                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3259                                         assert!(failed_htlcs.insert(payment_hash.0));
3260                                 },
3261                                 _ => panic!("Unexpected event"),
3262                         }
3263                         match events[3] {
3264                                 Event::PaymentFailed { ref payment_hash, .. } => {
3265                                         assert_eq!(*payment_hash, second_payment_hash);
3266                                 },
3267                                 _ => panic!("Unexpected event"),
3268                         }
3269                         match events[4] {
3270                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3271                                         assert!(failed_htlcs.insert(payment_hash.0));
3272                                 },
3273                                 _ => panic!("Unexpected event"),
3274                         }
3275                         match events[5] {
3276                                 Event::PaymentFailed { ref payment_hash, .. } => {
3277                                         assert_eq!(*payment_hash, third_payment_hash);
3278                                 },
3279                                 _ => panic!("Unexpected event"),
3280                         }
3281                 },
3282                 _ => panic!("Unexpected event"),
3283         }
3284
3285         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3286         match events[0] {
3287                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3288                 _ => panic!("Unexpected event"),
3289         }
3290
3291         assert!(failed_htlcs.contains(&first_payment_hash.0));
3292         assert!(failed_htlcs.contains(&second_payment_hash.0));
3293         assert!(failed_htlcs.contains(&third_payment_hash.0));
3294 }
3295
3296 #[test]
3297 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3298         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3299         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3300         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3301         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3302 }
3303
3304 #[test]
3305 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3306         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3307         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3308         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3309         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3310 }
3311
3312 #[test]
3313 fn fail_backward_pending_htlc_upon_channel_failure() {
3314         let chanmon_cfgs = create_chanmon_cfgs(2);
3315         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3316         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3317         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3318         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3319
3320         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3321         {
3322                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3323                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
3324                 check_added_monitors!(nodes[0], 1);
3325
3326                 let payment_event = {
3327                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3328                         assert_eq!(events.len(), 1);
3329                         SendEvent::from_event(events.remove(0))
3330                 };
3331                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3332                 assert_eq!(payment_event.msgs.len(), 1);
3333         }
3334
3335         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3336         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3337         {
3338                 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3339                 check_added_monitors!(nodes[0], 0);
3340
3341                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3342         }
3343
3344         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3345         {
3346                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3347
3348                 let secp_ctx = Secp256k1::new();
3349                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3350                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3351                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3352                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3353                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3354
3355                 // Send a 0-msat update_add_htlc to fail the channel.
3356                 let update_add_htlc = msgs::UpdateAddHTLC {
3357                         channel_id: chan.2,
3358                         htlc_id: 0,
3359                         amount_msat: 0,
3360                         payment_hash,
3361                         cltv_expiry,
3362                         onion_routing_packet,
3363                 };
3364                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3365         }
3366         let events = nodes[0].node.get_and_clear_pending_events();
3367         assert_eq!(events.len(), 3);
3368         // Check that Alice fails backward the pending HTLC from the second payment.
3369         match events[0] {
3370                 Event::PaymentPathFailed { payment_hash, .. } => {
3371                         assert_eq!(payment_hash, failed_payment_hash);
3372                 },
3373                 _ => panic!("Unexpected event"),
3374         }
3375         match events[1] {
3376                 Event::PaymentFailed { payment_hash, .. } => {
3377                         assert_eq!(payment_hash, failed_payment_hash);
3378                 },
3379                 _ => panic!("Unexpected event"),
3380         }
3381         match events[2] {
3382                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3383                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3384                 },
3385                 _ => panic!("Unexpected event {:?}", events[1]),
3386         }
3387         check_closed_broadcast!(nodes[0], true);
3388         check_added_monitors!(nodes[0], 1);
3389 }
3390
3391 #[test]
3392 fn test_htlc_ignore_latest_remote_commitment() {
3393         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3394         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3395         let chanmon_cfgs = create_chanmon_cfgs(2);
3396         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3397         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3398         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3399         if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3400                 // We rely on the ability to connect a block redundantly, which isn't allowed via
3401                 // `chain::Listen`, so we never run the test if we randomly get assigned that
3402                 // connect_style.
3403                 return;
3404         }
3405         create_announced_chan_between_nodes(&nodes, 0, 1);
3406
3407         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3408         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3409         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3410         check_closed_broadcast!(nodes[0], true);
3411         check_added_monitors!(nodes[0], 1);
3412         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3413
3414         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3415         assert_eq!(node_txn.len(), 3);
3416         assert_eq!(node_txn[0], node_txn[1]);
3417
3418         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
3419         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3420         check_closed_broadcast!(nodes[1], true);
3421         check_added_monitors!(nodes[1], 1);
3422         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3423
3424         // Duplicate the connect_block call since this may happen due to other listeners
3425         // registering new transactions
3426         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3427 }
3428
3429 #[test]
3430 fn test_force_close_fail_back() {
3431         // Check which HTLCs are failed-backwards on channel force-closure
3432         let chanmon_cfgs = create_chanmon_cfgs(3);
3433         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3434         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3435         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3436         create_announced_chan_between_nodes(&nodes, 0, 1);
3437         create_announced_chan_between_nodes(&nodes, 1, 2);
3438
3439         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3440
3441         let mut payment_event = {
3442                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3443                 check_added_monitors!(nodes[0], 1);
3444
3445                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3446                 assert_eq!(events.len(), 1);
3447                 SendEvent::from_event(events.remove(0))
3448         };
3449
3450         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3451         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3452
3453         expect_pending_htlcs_forwardable!(nodes[1]);
3454
3455         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3456         assert_eq!(events_2.len(), 1);
3457         payment_event = SendEvent::from_event(events_2.remove(0));
3458         assert_eq!(payment_event.msgs.len(), 1);
3459
3460         check_added_monitors!(nodes[1], 1);
3461         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3462         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3463         check_added_monitors!(nodes[2], 1);
3464         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3465
3466         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3467         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3468         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3469
3470         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3471         check_closed_broadcast!(nodes[2], true);
3472         check_added_monitors!(nodes[2], 1);
3473         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3474         let tx = {
3475                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3476                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3477                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3478                 // back to nodes[1] upon timeout otherwise.
3479                 assert_eq!(node_txn.len(), 1);
3480                 node_txn.remove(0)
3481         };
3482
3483         mine_transaction(&nodes[1], &tx);
3484
3485         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3486         check_closed_broadcast!(nodes[1], true);
3487         check_added_monitors!(nodes[1], 1);
3488         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3489
3490         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3491         {
3492                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3493                         .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);
3494         }
3495         mine_transaction(&nodes[2], &tx);
3496         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3497         assert_eq!(node_txn.len(), 1);
3498         assert_eq!(node_txn[0].input.len(), 1);
3499         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3500         assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3501         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3502
3503         check_spends!(node_txn[0], tx);
3504 }
3505
3506 #[test]
3507 fn test_dup_events_on_peer_disconnect() {
3508         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3509         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3510         // as we used to generate the event immediately upon receipt of the payment preimage in the
3511         // update_fulfill_htlc message.
3512
3513         let chanmon_cfgs = create_chanmon_cfgs(2);
3514         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3515         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3516         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3517         create_announced_chan_between_nodes(&nodes, 0, 1);
3518
3519         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3520
3521         nodes[1].node.claim_funds(payment_preimage);
3522         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3523         check_added_monitors!(nodes[1], 1);
3524         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3525         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3526         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3527
3528         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3529         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3530
3531         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3532         expect_payment_path_successful!(nodes[0]);
3533 }
3534
3535 #[test]
3536 fn test_peer_disconnected_before_funding_broadcasted() {
3537         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3538         // before the funding transaction has been broadcasted.
3539         let chanmon_cfgs = create_chanmon_cfgs(2);
3540         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3541         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3542         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3543
3544         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3545         // broadcasted, even though it's created by `nodes[0]`.
3546         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();
3547         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3548         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3549         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3550         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3551
3552         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3553         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3554
3555         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3556
3557         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3558         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3559
3560         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3561         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3562         // broadcasted.
3563         {
3564                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3565         }
3566
3567         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3568         // disconnected before the funding transaction was broadcasted.
3569         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3570         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3571
3572         check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3573         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3574 }
3575
3576 #[test]
3577 fn test_simple_peer_disconnect() {
3578         // Test that we can reconnect when there are no lost messages
3579         let chanmon_cfgs = create_chanmon_cfgs(3);
3580         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3581         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3582         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3583         create_announced_chan_between_nodes(&nodes, 0, 1);
3584         create_announced_chan_between_nodes(&nodes, 1, 2);
3585
3586         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3587         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3588         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3589
3590         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3591         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3592         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3593         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3594
3595         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3596         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3597         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3598
3599         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3600         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3601         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3602         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3603
3604         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3605         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3606
3607         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3608         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3609
3610         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3611         {
3612                 let events = nodes[0].node.get_and_clear_pending_events();
3613                 assert_eq!(events.len(), 4);
3614                 match events[0] {
3615                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3616                                 assert_eq!(payment_preimage, payment_preimage_3);
3617                                 assert_eq!(payment_hash, payment_hash_3);
3618                         },
3619                         _ => panic!("Unexpected event"),
3620                 }
3621                 match events[1] {
3622                         Event::PaymentPathSuccessful { .. } => {},
3623                         _ => panic!("Unexpected event"),
3624                 }
3625                 match events[2] {
3626                         Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3627                                 assert_eq!(payment_hash, payment_hash_5);
3628                                 assert!(payment_failed_permanently);
3629                         },
3630                         _ => panic!("Unexpected event"),
3631                 }
3632                 match events[3] {
3633                         Event::PaymentFailed { payment_hash, .. } => {
3634                                 assert_eq!(payment_hash, payment_hash_5);
3635                         },
3636                         _ => panic!("Unexpected event"),
3637                 }
3638         }
3639
3640         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3641         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3642 }
3643
3644 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3645         // Test that we can reconnect when in-flight HTLC updates get dropped
3646         let chanmon_cfgs = create_chanmon_cfgs(2);
3647         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3648         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3649         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3650
3651         let mut as_channel_ready = None;
3652         let channel_id = if messages_delivered == 0 {
3653                 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3654                 as_channel_ready = Some(channel_ready);
3655                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3656                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3657                 // it before the channel_reestablish message.
3658                 chan_id
3659         } else {
3660                 create_announced_chan_between_nodes(&nodes, 0, 1).2
3661         };
3662
3663         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3664
3665         let payment_event = {
3666                 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3667                 check_added_monitors!(nodes[0], 1);
3668
3669                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3670                 assert_eq!(events.len(), 1);
3671                 SendEvent::from_event(events.remove(0))
3672         };
3673         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3674
3675         if messages_delivered < 2 {
3676                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3677         } else {
3678                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3679                 if messages_delivered >= 3 {
3680                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3681                         check_added_monitors!(nodes[1], 1);
3682                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3683
3684                         if messages_delivered >= 4 {
3685                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3686                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3687                                 check_added_monitors!(nodes[0], 1);
3688
3689                                 if messages_delivered >= 5 {
3690                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3691                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3692                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3693                                         check_added_monitors!(nodes[0], 1);
3694
3695                                         if messages_delivered >= 6 {
3696                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3697                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3698                                                 check_added_monitors!(nodes[1], 1);
3699                                         }
3700                                 }
3701                         }
3702                 }
3703         }
3704
3705         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3706         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3707         if messages_delivered < 3 {
3708                 if simulate_broken_lnd {
3709                         // lnd has a long-standing bug where they send a channel_ready prior to a
3710                         // channel_reestablish if you reconnect prior to channel_ready time.
3711                         //
3712                         // Here we simulate that behavior, delivering a channel_ready immediately on
3713                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3714                         // in `reconnect_nodes` but we currently don't fail based on that.
3715                         //
3716                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3717                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3718                 }
3719                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3720                 // received on either side, both sides will need to resend them.
3721                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3722         } else if messages_delivered == 3 {
3723                 // nodes[0] still wants its RAA + commitment_signed
3724                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3725         } else if messages_delivered == 4 {
3726                 // nodes[0] still wants its commitment_signed
3727                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3728         } else if messages_delivered == 5 {
3729                 // nodes[1] still wants its final RAA
3730                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3731         } else if messages_delivered == 6 {
3732                 // Everything was delivered...
3733                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3734         }
3735
3736         let events_1 = nodes[1].node.get_and_clear_pending_events();
3737         if messages_delivered == 0 {
3738                 assert_eq!(events_1.len(), 2);
3739                 match events_1[0] {
3740                         Event::ChannelReady { .. } => { },
3741                         _ => panic!("Unexpected event"),
3742                 };
3743                 match events_1[1] {
3744                         Event::PendingHTLCsForwardable { .. } => { },
3745                         _ => panic!("Unexpected event"),
3746                 };
3747         } else {
3748                 assert_eq!(events_1.len(), 1);
3749                 match events_1[0] {
3750                         Event::PendingHTLCsForwardable { .. } => { },
3751                         _ => panic!("Unexpected event"),
3752                 };
3753         }
3754
3755         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3756         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3757         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3758
3759         nodes[1].node.process_pending_htlc_forwards();
3760
3761         let events_2 = nodes[1].node.get_and_clear_pending_events();
3762         assert_eq!(events_2.len(), 1);
3763         match events_2[0] {
3764                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
3765                         assert_eq!(payment_hash_1, *payment_hash);
3766                         assert_eq!(amount_msat, 1_000_000);
3767                         assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3768                         assert_eq!(via_channel_id, Some(channel_id));
3769                         match &purpose {
3770                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3771                                         assert!(payment_preimage.is_none());
3772                                         assert_eq!(payment_secret_1, *payment_secret);
3773                                 },
3774                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3775                         }
3776                 },
3777                 _ => panic!("Unexpected event"),
3778         }
3779
3780         nodes[1].node.claim_funds(payment_preimage_1);
3781         check_added_monitors!(nodes[1], 1);
3782         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3783
3784         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3785         assert_eq!(events_3.len(), 1);
3786         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3787                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3788                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3789                         assert!(updates.update_add_htlcs.is_empty());
3790                         assert!(updates.update_fail_htlcs.is_empty());
3791                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3792                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3793                         assert!(updates.update_fee.is_none());
3794                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3795                 },
3796                 _ => panic!("Unexpected event"),
3797         };
3798
3799         if messages_delivered >= 1 {
3800                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3801
3802                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3803                 assert_eq!(events_4.len(), 1);
3804                 match events_4[0] {
3805                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3806                                 assert_eq!(payment_preimage_1, *payment_preimage);
3807                                 assert_eq!(payment_hash_1, *payment_hash);
3808                         },
3809                         _ => panic!("Unexpected event"),
3810                 }
3811
3812                 if messages_delivered >= 2 {
3813                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3814                         check_added_monitors!(nodes[0], 1);
3815                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3816
3817                         if messages_delivered >= 3 {
3818                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3819                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3820                                 check_added_monitors!(nodes[1], 1);
3821
3822                                 if messages_delivered >= 4 {
3823                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3824                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3825                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3826                                         check_added_monitors!(nodes[1], 1);
3827
3828                                         if messages_delivered >= 5 {
3829                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3830                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3831                                                 check_added_monitors!(nodes[0], 1);
3832                                         }
3833                                 }
3834                         }
3835                 }
3836         }
3837
3838         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3839         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3840         if messages_delivered < 2 {
3841                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3842                 if messages_delivered < 1 {
3843                         expect_payment_sent!(nodes[0], payment_preimage_1);
3844                 } else {
3845                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3846                 }
3847         } else if messages_delivered == 2 {
3848                 // nodes[0] still wants its RAA + commitment_signed
3849                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3850         } else if messages_delivered == 3 {
3851                 // nodes[0] still wants its commitment_signed
3852                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3853         } else if messages_delivered == 4 {
3854                 // nodes[1] still wants its final RAA
3855                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3856         } else if messages_delivered == 5 {
3857                 // Everything was delivered...
3858                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3859         }
3860
3861         if messages_delivered == 1 || messages_delivered == 2 {
3862                 expect_payment_path_successful!(nodes[0]);
3863         }
3864         if messages_delivered <= 5 {
3865                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3866                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3867         }
3868         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3869
3870         if messages_delivered > 2 {
3871                 expect_payment_path_successful!(nodes[0]);
3872         }
3873
3874         // Channel should still work fine...
3875         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3876         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3877         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3878 }
3879
3880 #[test]
3881 fn test_drop_messages_peer_disconnect_a() {
3882         do_test_drop_messages_peer_disconnect(0, true);
3883         do_test_drop_messages_peer_disconnect(0, false);
3884         do_test_drop_messages_peer_disconnect(1, false);
3885         do_test_drop_messages_peer_disconnect(2, false);
3886 }
3887
3888 #[test]
3889 fn test_drop_messages_peer_disconnect_b() {
3890         do_test_drop_messages_peer_disconnect(3, false);
3891         do_test_drop_messages_peer_disconnect(4, false);
3892         do_test_drop_messages_peer_disconnect(5, false);
3893         do_test_drop_messages_peer_disconnect(6, false);
3894 }
3895
3896 #[test]
3897 fn test_channel_ready_without_best_block_updated() {
3898         // Previously, if we were offline when a funding transaction was locked in, and then we came
3899         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3900         // generate a channel_ready until a later best_block_updated. This tests that we generate the
3901         // channel_ready immediately instead.
3902         let chanmon_cfgs = create_chanmon_cfgs(2);
3903         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3904         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3905         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3906         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3907
3908         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
3909
3910         let conf_height = nodes[0].best_block_info().1 + 1;
3911         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3912         let block_txn = [funding_tx];
3913         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3914         let conf_block_header = nodes[0].get_block_header(conf_height);
3915         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3916
3917         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
3918         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
3919         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3920 }
3921
3922 #[test]
3923 fn test_drop_messages_peer_disconnect_dual_htlc() {
3924         // Test that we can handle reconnecting when both sides of a channel have pending
3925         // commitment_updates when we disconnect.
3926         let chanmon_cfgs = create_chanmon_cfgs(2);
3927         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3928         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3929         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3930         create_announced_chan_between_nodes(&nodes, 0, 1);
3931
3932         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3933
3934         // Now try to send a second payment which will fail to send
3935         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3936         nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
3937         check_added_monitors!(nodes[0], 1);
3938
3939         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3940         assert_eq!(events_1.len(), 1);
3941         match events_1[0] {
3942                 MessageSendEvent::UpdateHTLCs { .. } => {},
3943                 _ => panic!("Unexpected event"),
3944         }
3945
3946         nodes[1].node.claim_funds(payment_preimage_1);
3947         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3948         check_added_monitors!(nodes[1], 1);
3949
3950         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3951         assert_eq!(events_2.len(), 1);
3952         match events_2[0] {
3953                 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 } } => {
3954                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3955                         assert!(update_add_htlcs.is_empty());
3956                         assert_eq!(update_fulfill_htlcs.len(), 1);
3957                         assert!(update_fail_htlcs.is_empty());
3958                         assert!(update_fail_malformed_htlcs.is_empty());
3959                         assert!(update_fee.is_none());
3960
3961                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3962                         let events_3 = nodes[0].node.get_and_clear_pending_events();
3963                         assert_eq!(events_3.len(), 1);
3964                         match events_3[0] {
3965                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3966                                         assert_eq!(*payment_preimage, payment_preimage_1);
3967                                         assert_eq!(*payment_hash, payment_hash_1);
3968                                 },
3969                                 _ => panic!("Unexpected event"),
3970                         }
3971
3972                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3973                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3974                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3975                         check_added_monitors!(nodes[0], 1);
3976                 },
3977                 _ => panic!("Unexpected event"),
3978         }
3979
3980         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3981         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3982
3983         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();
3984         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3985         assert_eq!(reestablish_1.len(), 1);
3986         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();
3987         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3988         assert_eq!(reestablish_2.len(), 1);
3989
3990         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3991         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3992         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3993         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3994
3995         assert!(as_resp.0.is_none());
3996         assert!(bs_resp.0.is_none());
3997
3998         assert!(bs_resp.1.is_none());
3999         assert!(bs_resp.2.is_none());
4000
4001         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4002
4003         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4004         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4005         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4006         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4007         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4008         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4009         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4010         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4011         // No commitment_signed so get_event_msg's assert(len == 1) passes
4012         check_added_monitors!(nodes[1], 1);
4013
4014         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4015         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4016         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4017         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4018         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4019         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4020         assert!(bs_second_commitment_signed.update_fee.is_none());
4021         check_added_monitors!(nodes[1], 1);
4022
4023         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4024         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4025         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4026         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4027         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4028         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4029         assert!(as_commitment_signed.update_fee.is_none());
4030         check_added_monitors!(nodes[0], 1);
4031
4032         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4033         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4034         // No commitment_signed so get_event_msg's assert(len == 1) passes
4035         check_added_monitors!(nodes[0], 1);
4036
4037         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4038         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4039         // No commitment_signed so get_event_msg's assert(len == 1) passes
4040         check_added_monitors!(nodes[1], 1);
4041
4042         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4043         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4044         check_added_monitors!(nodes[1], 1);
4045
4046         expect_pending_htlcs_forwardable!(nodes[1]);
4047
4048         let events_5 = nodes[1].node.get_and_clear_pending_events();
4049         assert_eq!(events_5.len(), 1);
4050         match events_5[0] {
4051                 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4052                         assert_eq!(payment_hash_2, *payment_hash);
4053                         match &purpose {
4054                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4055                                         assert!(payment_preimage.is_none());
4056                                         assert_eq!(payment_secret_2, *payment_secret);
4057                                 },
4058                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4059                         }
4060                 },
4061                 _ => panic!("Unexpected event"),
4062         }
4063
4064         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4065         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4066         check_added_monitors!(nodes[0], 1);
4067
4068         expect_payment_path_successful!(nodes[0]);
4069         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4070 }
4071
4072 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4073         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4074         // to avoid our counterparty failing the channel.
4075         let chanmon_cfgs = create_chanmon_cfgs(2);
4076         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4077         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4078         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4079
4080         create_announced_chan_between_nodes(&nodes, 0, 1);
4081
4082         let our_payment_hash = if send_partial_mpp {
4083                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4084                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4085                 // indicates there are more HTLCs coming.
4086                 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.
4087                 let payment_id = PaymentId([42; 32]);
4088                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(payment_secret), payment_id, &route).unwrap();
4089                 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();
4090                 check_added_monitors!(nodes[0], 1);
4091                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4092                 assert_eq!(events.len(), 1);
4093                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4094                 // hop should *not* yet generate any PaymentClaimable event(s).
4095                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4096                 our_payment_hash
4097         } else {
4098                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4099         };
4100
4101         let mut block = Block {
4102                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
4103                 txdata: vec![],
4104         };
4105         connect_block(&nodes[0], &block);
4106         connect_block(&nodes[1], &block);
4107         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4108         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4109                 block.header.prev_blockhash = block.block_hash();
4110                 connect_block(&nodes[0], &block);
4111                 connect_block(&nodes[1], &block);
4112         }
4113
4114         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4115
4116         check_added_monitors!(nodes[1], 1);
4117         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4118         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4119         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4120         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4121         assert!(htlc_timeout_updates.update_fee.is_none());
4122
4123         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4124         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4125         // 100_000 msat as u64, followed by the height at which we failed back above
4126         let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4127         expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4128         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4129 }
4130
4131 #[test]
4132 fn test_htlc_timeout() {
4133         do_test_htlc_timeout(true);
4134         do_test_htlc_timeout(false);
4135 }
4136
4137 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4138         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4139         let chanmon_cfgs = create_chanmon_cfgs(3);
4140         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4141         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4142         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4143         create_announced_chan_between_nodes(&nodes, 0, 1);
4144         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4145
4146         // Make sure all nodes are at the same starting height
4147         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4148         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4149         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4150
4151         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4152         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4153         {
4154                 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4155         }
4156         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4157         check_added_monitors!(nodes[1], 1);
4158
4159         // Now attempt to route a second payment, which should be placed in the holding cell
4160         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4161         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4162         sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4163         if forwarded_htlc {
4164                 check_added_monitors!(nodes[0], 1);
4165                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4166                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4167                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4168                 expect_pending_htlcs_forwardable!(nodes[1]);
4169         }
4170         check_added_monitors!(nodes[1], 0);
4171
4172         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4173         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4174         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4175         connect_blocks(&nodes[1], 1);
4176
4177         if forwarded_htlc {
4178                 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 }]);
4179                 check_added_monitors!(nodes[1], 1);
4180                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4181                 assert_eq!(fail_commit.len(), 1);
4182                 match fail_commit[0] {
4183                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4184                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4185                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4186                         },
4187                         _ => unreachable!(),
4188                 }
4189                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4190         } else {
4191                 expect_payment_failed!(nodes[1], second_payment_hash, false);
4192         }
4193 }
4194
4195 #[test]
4196 fn test_holding_cell_htlc_add_timeouts() {
4197         do_test_holding_cell_htlc_add_timeouts(false);
4198         do_test_holding_cell_htlc_add_timeouts(true);
4199 }
4200
4201 macro_rules! check_spendable_outputs {
4202         ($node: expr, $keysinterface: expr) => {
4203                 {
4204                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4205                         let mut txn = Vec::new();
4206                         let mut all_outputs = Vec::new();
4207                         let secp_ctx = Secp256k1::new();
4208                         for event in events.drain(..) {
4209                                 match event {
4210                                         Event::SpendableOutputs { mut outputs } => {
4211                                                 for outp in outputs.drain(..) {
4212                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4213                                                         all_outputs.push(outp);
4214                                                 }
4215                                         },
4216                                         _ => panic!("Unexpected event"),
4217                                 };
4218                         }
4219                         if all_outputs.len() > 1 {
4220                                 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) {
4221                                         txn.push(tx);
4222                                 }
4223                         }
4224                         txn
4225                 }
4226         }
4227 }
4228
4229 #[test]
4230 fn test_claim_sizeable_push_msat() {
4231         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4232         let chanmon_cfgs = create_chanmon_cfgs(2);
4233         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4234         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4235         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4236
4237         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4238         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4239         check_closed_broadcast!(nodes[1], true);
4240         check_added_monitors!(nodes[1], 1);
4241         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4242         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4243         assert_eq!(node_txn.len(), 1);
4244         check_spends!(node_txn[0], chan.3);
4245         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
4246
4247         mine_transaction(&nodes[1], &node_txn[0]);
4248         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4249
4250         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4251         assert_eq!(spend_txn.len(), 1);
4252         assert_eq!(spend_txn[0].input.len(), 1);
4253         check_spends!(spend_txn[0], node_txn[0]);
4254         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4255 }
4256
4257 #[test]
4258 fn test_claim_on_remote_sizeable_push_msat() {
4259         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4260         // to_remote output is encumbered by a P2WPKH
4261         let chanmon_cfgs = create_chanmon_cfgs(2);
4262         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4263         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4264         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4265
4266         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4267         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4268         check_closed_broadcast!(nodes[0], true);
4269         check_added_monitors!(nodes[0], 1);
4270         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4271
4272         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4273         assert_eq!(node_txn.len(), 1);
4274         check_spends!(node_txn[0], chan.3);
4275         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
4276
4277         mine_transaction(&nodes[1], &node_txn[0]);
4278         check_closed_broadcast!(nodes[1], true);
4279         check_added_monitors!(nodes[1], 1);
4280         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4281         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4282
4283         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4284         assert_eq!(spend_txn.len(), 1);
4285         check_spends!(spend_txn[0], node_txn[0]);
4286 }
4287
4288 #[test]
4289 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4290         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4291         // to_remote output is encumbered by a P2WPKH
4292
4293         let chanmon_cfgs = create_chanmon_cfgs(2);
4294         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4295         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4296         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4297
4298         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4299         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4300         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4301         assert_eq!(revoked_local_txn[0].input.len(), 1);
4302         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4303
4304         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4305         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4306         check_closed_broadcast!(nodes[1], true);
4307         check_added_monitors!(nodes[1], 1);
4308         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4309
4310         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4311         mine_transaction(&nodes[1], &node_txn[0]);
4312         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4313
4314         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4315         assert_eq!(spend_txn.len(), 3);
4316         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4317         check_spends!(spend_txn[1], node_txn[0]);
4318         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4319 }
4320
4321 #[test]
4322 fn test_static_spendable_outputs_preimage_tx() {
4323         let chanmon_cfgs = create_chanmon_cfgs(2);
4324         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4325         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4326         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4327
4328         // Create some initial channels
4329         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4330
4331         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4332
4333         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4334         assert_eq!(commitment_tx[0].input.len(), 1);
4335         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4336
4337         // Settle A's commitment tx on B's chain
4338         nodes[1].node.claim_funds(payment_preimage);
4339         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4340         check_added_monitors!(nodes[1], 1);
4341         mine_transaction(&nodes[1], &commitment_tx[0]);
4342         check_added_monitors!(nodes[1], 1);
4343         let events = nodes[1].node.get_and_clear_pending_msg_events();
4344         match events[0] {
4345                 MessageSendEvent::UpdateHTLCs { .. } => {},
4346                 _ => panic!("Unexpected event"),
4347         }
4348         match events[1] {
4349                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4350                 _ => panic!("Unexepected event"),
4351         }
4352
4353         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4354         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4355         assert_eq!(node_txn.len(), 1);
4356         check_spends!(node_txn[0], commitment_tx[0]);
4357         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4358
4359         mine_transaction(&nodes[1], &node_txn[0]);
4360         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4361         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4362
4363         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4364         assert_eq!(spend_txn.len(), 1);
4365         check_spends!(spend_txn[0], node_txn[0]);
4366 }
4367
4368 #[test]
4369 fn test_static_spendable_outputs_timeout_tx() {
4370         let chanmon_cfgs = create_chanmon_cfgs(2);
4371         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4372         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4373         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4374
4375         // Create some initial channels
4376         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4377
4378         // Rebalance the network a bit by relaying one payment through all the channels ...
4379         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4380
4381         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4382
4383         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4384         assert_eq!(commitment_tx[0].input.len(), 1);
4385         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4386
4387         // Settle A's commitment tx on B' chain
4388         mine_transaction(&nodes[1], &commitment_tx[0]);
4389         check_added_monitors!(nodes[1], 1);
4390         let events = nodes[1].node.get_and_clear_pending_msg_events();
4391         match events[0] {
4392                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4393                 _ => panic!("Unexpected event"),
4394         }
4395         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4396
4397         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4398         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4399         assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4400         check_spends!(node_txn[0],  commitment_tx[0].clone());
4401         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4402
4403         mine_transaction(&nodes[1], &node_txn[0]);
4404         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4405         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4406         expect_payment_failed!(nodes[1], our_payment_hash, false);
4407
4408         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4409         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4410         check_spends!(spend_txn[0], commitment_tx[0]);
4411         check_spends!(spend_txn[1], node_txn[0]);
4412         check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4413 }
4414
4415 #[test]
4416 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4417         let chanmon_cfgs = create_chanmon_cfgs(2);
4418         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4419         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4420         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4421
4422         // Create some initial channels
4423         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4424
4425         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4426         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4427         assert_eq!(revoked_local_txn[0].input.len(), 1);
4428         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4429
4430         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4431
4432         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4433         check_closed_broadcast!(nodes[1], true);
4434         check_added_monitors!(nodes[1], 1);
4435         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4436
4437         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4438         assert_eq!(node_txn.len(), 1);
4439         assert_eq!(node_txn[0].input.len(), 2);
4440         check_spends!(node_txn[0], revoked_local_txn[0]);
4441
4442         mine_transaction(&nodes[1], &node_txn[0]);
4443         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4444
4445         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4446         assert_eq!(spend_txn.len(), 1);
4447         check_spends!(spend_txn[0], node_txn[0]);
4448 }
4449
4450 #[test]
4451 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4452         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4453         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4454         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4455         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4456         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4457
4458         // Create some initial channels
4459         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4460
4461         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4462         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4463         assert_eq!(revoked_local_txn[0].input.len(), 1);
4464         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4465
4466         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4467
4468         // A will generate HTLC-Timeout from revoked commitment tx
4469         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4470         check_closed_broadcast!(nodes[0], true);
4471         check_added_monitors!(nodes[0], 1);
4472         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4473         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4474
4475         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4476         assert_eq!(revoked_htlc_txn.len(), 1);
4477         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4478         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4479         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4480         assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4481
4482         // B will generate justice tx from A's revoked commitment/HTLC tx
4483         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4484         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4485         check_closed_broadcast!(nodes[1], true);
4486         check_added_monitors!(nodes[1], 1);
4487         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4488
4489         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4490         assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4491         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4492         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4493         // transactions next...
4494         assert_eq!(node_txn[0].input.len(), 3);
4495         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4496
4497         assert_eq!(node_txn[1].input.len(), 2);
4498         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4499         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4500                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4501         } else {
4502                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4503                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4504         }
4505
4506         mine_transaction(&nodes[1], &node_txn[1]);
4507         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4508
4509         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4510         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4511         assert_eq!(spend_txn.len(), 1);
4512         assert_eq!(spend_txn[0].input.len(), 1);
4513         check_spends!(spend_txn[0], node_txn[1]);
4514 }
4515
4516 #[test]
4517 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4518         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4519         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4520         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4521         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4522         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4523
4524         // Create some initial channels
4525         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4526
4527         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4528         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4529         assert_eq!(revoked_local_txn[0].input.len(), 1);
4530         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4531
4532         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4533         assert_eq!(revoked_local_txn[0].output.len(), 2);
4534
4535         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4536
4537         // B will generate HTLC-Success from revoked commitment tx
4538         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4539         check_closed_broadcast!(nodes[1], true);
4540         check_added_monitors!(nodes[1], 1);
4541         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4542         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4543
4544         assert_eq!(revoked_htlc_txn.len(), 1);
4545         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4546         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4547         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4548
4549         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4550         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4551         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4552
4553         // A will generate justice tx from B's revoked commitment/HTLC tx
4554         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4555         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4556         check_closed_broadcast!(nodes[0], true);
4557         check_added_monitors!(nodes[0], 1);
4558         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4559
4560         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4561         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4562
4563         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4564         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4565         // transactions next...
4566         assert_eq!(node_txn[0].input.len(), 2);
4567         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4568         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4569                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4570         } else {
4571                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4572                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4573         }
4574
4575         assert_eq!(node_txn[1].input.len(), 1);
4576         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4577
4578         mine_transaction(&nodes[0], &node_txn[1]);
4579         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4580
4581         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4582         // didn't try to generate any new transactions.
4583
4584         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4585         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4586         assert_eq!(spend_txn.len(), 3);
4587         assert_eq!(spend_txn[0].input.len(), 1);
4588         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4589         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4590         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4591         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4592 }
4593
4594 #[test]
4595 fn test_onchain_to_onchain_claim() {
4596         // Test that in case of channel closure, we detect the state of output and claim HTLC
4597         // on downstream peer's remote commitment tx.
4598         // First, have C claim an HTLC against its own latest commitment transaction.
4599         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4600         // channel.
4601         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4602         // gets broadcast.
4603
4604         let chanmon_cfgs = create_chanmon_cfgs(3);
4605         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4606         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4607         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4608
4609         // Create some initial channels
4610         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4611         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4612
4613         // Ensure all nodes are at the same height
4614         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4615         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4616         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4617         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4618
4619         // Rebalance the network a bit by relaying one payment through all the channels ...
4620         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4621         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4622
4623         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4624         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4625         check_spends!(commitment_tx[0], chan_2.3);
4626         nodes[2].node.claim_funds(payment_preimage);
4627         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4628         check_added_monitors!(nodes[2], 1);
4629         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4630         assert!(updates.update_add_htlcs.is_empty());
4631         assert!(updates.update_fail_htlcs.is_empty());
4632         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4633         assert!(updates.update_fail_malformed_htlcs.is_empty());
4634
4635         mine_transaction(&nodes[2], &commitment_tx[0]);
4636         check_closed_broadcast!(nodes[2], true);
4637         check_added_monitors!(nodes[2], 1);
4638         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4639
4640         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4641         assert_eq!(c_txn.len(), 1);
4642         check_spends!(c_txn[0], commitment_tx[0]);
4643         assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4644         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4645         assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4646
4647         // 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
4648         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
4649         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone(), c_txn[0].clone()]});
4650         check_added_monitors!(nodes[1], 1);
4651         let events = nodes[1].node.get_and_clear_pending_events();
4652         assert_eq!(events.len(), 2);
4653         match events[0] {
4654                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4655                 _ => panic!("Unexpected event"),
4656         }
4657         match events[1] {
4658                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4659                         assert_eq!(fee_earned_msat, Some(1000));
4660                         assert_eq!(prev_channel_id, Some(chan_1.2));
4661                         assert_eq!(claim_from_onchain_tx, true);
4662                         assert_eq!(next_channel_id, Some(chan_2.2));
4663                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4664                 },
4665                 _ => panic!("Unexpected event"),
4666         }
4667         check_added_monitors!(nodes[1], 1);
4668         let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4669         assert_eq!(msg_events.len(), 3);
4670         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4671         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4672
4673         match nodes_2_event {
4674                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4675                 _ => panic!("Unexpected event"),
4676         }
4677
4678         match nodes_0_event {
4679                 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, .. } } => {
4680                         assert!(update_add_htlcs.is_empty());
4681                         assert!(update_fail_htlcs.is_empty());
4682                         assert_eq!(update_fulfill_htlcs.len(), 1);
4683                         assert!(update_fail_malformed_htlcs.is_empty());
4684                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4685                 },
4686                 _ => panic!("Unexpected event"),
4687         };
4688
4689         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4690         match msg_events[0] {
4691                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4692                 _ => panic!("Unexpected event"),
4693         }
4694
4695         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4696         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4697         mine_transaction(&nodes[1], &commitment_tx[0]);
4698         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4699         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4700         // ChannelMonitor: HTLC-Success tx
4701         assert_eq!(b_txn.len(), 1);
4702         check_spends!(b_txn[0], commitment_tx[0]);
4703         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4704         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4705         assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1 + 1); // Success tx
4706
4707         check_closed_broadcast!(nodes[1], true);
4708         check_added_monitors!(nodes[1], 1);
4709 }
4710
4711 #[test]
4712 fn test_duplicate_payment_hash_one_failure_one_success() {
4713         // Topology : A --> B --> C --> D
4714         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4715         // Note that because C will refuse to generate two payment secrets for the same payment hash,
4716         // we forward one of the payments onwards to D.
4717         let chanmon_cfgs = create_chanmon_cfgs(4);
4718         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4719         // When this test was written, the default base fee floated based on the HTLC count.
4720         // It is now fixed, so we simply set the fee to the expected value here.
4721         let mut config = test_default_channel_config();
4722         config.channel_config.forwarding_fee_base_msat = 196;
4723         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4724                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4725         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4726
4727         create_announced_chan_between_nodes(&nodes, 0, 1);
4728         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4729         create_announced_chan_between_nodes(&nodes, 2, 3);
4730
4731         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4732         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4733         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4734         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4735         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4736
4737         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4738
4739         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4740         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4741         // script push size limit so that the below script length checks match
4742         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4743         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4744                 .with_features(nodes[3].node.invoice_features());
4745         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000, TEST_FINAL_CLTV - 40);
4746         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4747
4748         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4749         assert_eq!(commitment_txn[0].input.len(), 1);
4750         check_spends!(commitment_txn[0], chan_2.3);
4751
4752         mine_transaction(&nodes[1], &commitment_txn[0]);
4753         check_closed_broadcast!(nodes[1], true);
4754         check_added_monitors!(nodes[1], 1);
4755         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4756         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
4757
4758         let htlc_timeout_tx;
4759         { // Extract one of the two HTLC-Timeout transaction
4760                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4761                 // ChannelMonitor: timeout tx * 2-or-3
4762                 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4763
4764                 check_spends!(node_txn[0], commitment_txn[0]);
4765                 assert_eq!(node_txn[0].input.len(), 1);
4766                 assert_eq!(node_txn[0].output.len(), 1);
4767
4768                 if node_txn.len() > 2 {
4769                         check_spends!(node_txn[1], commitment_txn[0]);
4770                         assert_eq!(node_txn[1].input.len(), 1);
4771                         assert_eq!(node_txn[1].output.len(), 1);
4772                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4773
4774                         check_spends!(node_txn[2], commitment_txn[0]);
4775                         assert_eq!(node_txn[2].input.len(), 1);
4776                         assert_eq!(node_txn[2].output.len(), 1);
4777                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4778                 } else {
4779                         check_spends!(node_txn[1], commitment_txn[0]);
4780                         assert_eq!(node_txn[1].input.len(), 1);
4781                         assert_eq!(node_txn[1].output.len(), 1);
4782                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4783                 }
4784
4785                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4786                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4787                 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
4788                 // (with value 900 sats) will be claimed in the below `claim_funds` call.
4789                 if node_txn.len() > 2 {
4790                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4791                         htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
4792                 } else {
4793                         htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
4794                 }
4795         }
4796
4797         nodes[2].node.claim_funds(our_payment_preimage);
4798         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4799
4800         mine_transaction(&nodes[2], &commitment_txn[0]);
4801         check_added_monitors!(nodes[2], 2);
4802         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4803         let events = nodes[2].node.get_and_clear_pending_msg_events();
4804         match events[0] {
4805                 MessageSendEvent::UpdateHTLCs { .. } => {},
4806                 _ => panic!("Unexpected event"),
4807         }
4808         match events[1] {
4809                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4810                 _ => panic!("Unexepected event"),
4811         }
4812         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4813         assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4814         check_spends!(htlc_success_txn[0], commitment_txn[0]);
4815         check_spends!(htlc_success_txn[1], commitment_txn[0]);
4816         assert_eq!(htlc_success_txn[0].input.len(), 1);
4817         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4818         assert_eq!(htlc_success_txn[1].input.len(), 1);
4819         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4820         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4821         assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4822
4823         mine_transaction(&nodes[1], &htlc_timeout_tx);
4824         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4825         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 }]);
4826         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4827         assert!(htlc_updates.update_add_htlcs.is_empty());
4828         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4829         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4830         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4831         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4832         check_added_monitors!(nodes[1], 1);
4833
4834         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4835         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4836         {
4837                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4838         }
4839         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
4840
4841         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4842         mine_transaction(&nodes[1], &htlc_success_txn[1]);
4843         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
4844         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4845         assert!(updates.update_add_htlcs.is_empty());
4846         assert!(updates.update_fail_htlcs.is_empty());
4847         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4848         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
4849         assert!(updates.update_fail_malformed_htlcs.is_empty());
4850         check_added_monitors!(nodes[1], 1);
4851
4852         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4853         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4854
4855         let events = nodes[0].node.get_and_clear_pending_events();
4856         match events[0] {
4857                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4858                         assert_eq!(*payment_preimage, our_payment_preimage);
4859                         assert_eq!(*payment_hash, duplicate_payment_hash);
4860                 }
4861                 _ => panic!("Unexpected event"),
4862         }
4863 }
4864
4865 #[test]
4866 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4867         let chanmon_cfgs = create_chanmon_cfgs(2);
4868         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4869         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4870         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4871
4872         // Create some initial channels
4873         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4874
4875         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
4876         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4877         assert_eq!(local_txn.len(), 1);
4878         assert_eq!(local_txn[0].input.len(), 1);
4879         check_spends!(local_txn[0], chan_1.3);
4880
4881         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4882         nodes[1].node.claim_funds(payment_preimage);
4883         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
4884         check_added_monitors!(nodes[1], 1);
4885
4886         mine_transaction(&nodes[1], &local_txn[0]);
4887         check_added_monitors!(nodes[1], 1);
4888         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4889         let events = nodes[1].node.get_and_clear_pending_msg_events();
4890         match events[0] {
4891                 MessageSendEvent::UpdateHTLCs { .. } => {},
4892                 _ => panic!("Unexpected event"),
4893         }
4894         match events[1] {
4895                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4896                 _ => panic!("Unexepected event"),
4897         }
4898         let node_tx = {
4899                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4900                 assert_eq!(node_txn.len(), 1);
4901                 assert_eq!(node_txn[0].input.len(), 1);
4902                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4903                 check_spends!(node_txn[0], local_txn[0]);
4904                 node_txn[0].clone()
4905         };
4906
4907         mine_transaction(&nodes[1], &node_tx);
4908         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4909
4910         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4911         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4912         assert_eq!(spend_txn.len(), 1);
4913         assert_eq!(spend_txn[0].input.len(), 1);
4914         check_spends!(spend_txn[0], node_tx);
4915         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4916 }
4917
4918 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4919         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4920         // unrevoked commitment transaction.
4921         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4922         // a remote RAA before they could be failed backwards (and combinations thereof).
4923         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4924         // use the same payment hashes.
4925         // Thus, we use a six-node network:
4926         //
4927         // A \         / E
4928         //    - C - D -
4929         // B /         \ F
4930         // And test where C fails back to A/B when D announces its latest commitment transaction
4931         let chanmon_cfgs = create_chanmon_cfgs(6);
4932         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4933         // When this test was written, the default base fee floated based on the HTLC count.
4934         // It is now fixed, so we simply set the fee to the expected value here.
4935         let mut config = test_default_channel_config();
4936         config.channel_config.forwarding_fee_base_msat = 196;
4937         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
4938                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4939         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4940
4941         let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
4942         let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4943         let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
4944         let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
4945         let chan_3_5  = create_announced_chan_between_nodes(&nodes, 3, 5);
4946
4947         // Rebalance and check output sanity...
4948         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
4949         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
4950         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
4951
4952         let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
4953                 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
4954         // 0th HTLC:
4955         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
4956         // 1st HTLC:
4957         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
4958         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4959         // 2nd HTLC:
4960         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
4961         // 3rd HTLC:
4962         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
4963         // 4th HTLC:
4964         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4965         // 5th HTLC:
4966         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4967         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
4968         // 6th HTLC:
4969         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());
4970         // 7th HTLC:
4971         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());
4972
4973         // 8th HTLC:
4974         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4975         // 9th HTLC:
4976         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4977         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
4978
4979         // 10th HTLC:
4980         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
4981         // 11th HTLC:
4982         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
4983         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());
4984
4985         // Double-check that six of the new HTLC were added
4986         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
4987         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
4988         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
4989         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
4990
4991         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
4992         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
4993         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
4994         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
4995         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
4996         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
4997         check_added_monitors!(nodes[4], 0);
4998
4999         let failed_destinations = vec![
5000                 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5001                 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5002                 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5003                 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5004         ];
5005         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5006         check_added_monitors!(nodes[4], 1);
5007
5008         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5009         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5010         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5011         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5012         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5013         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5014
5015         // Fail 3rd below-dust and 7th above-dust HTLCs
5016         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5017         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5018         check_added_monitors!(nodes[5], 0);
5019
5020         let failed_destinations_2 = vec![
5021                 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5022                 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5023         ];
5024         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5025         check_added_monitors!(nodes[5], 1);
5026
5027         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5028         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5029         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5030         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5031
5032         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5033
5034         // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5035         let failed_destinations_3 = vec![
5036                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5037                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5038                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5039                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5040                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5041                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5042         ];
5043         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5044         check_added_monitors!(nodes[3], 1);
5045         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5046         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5047         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5048         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5049         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5050         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5051         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5052         if deliver_last_raa {
5053                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5054         } else {
5055                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5056         }
5057
5058         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5059         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5060         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5061         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5062         //
5063         // We now broadcast the latest commitment transaction, which *should* result in failures for
5064         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5065         // the non-broadcast above-dust HTLCs.
5066         //
5067         // Alternatively, we may broadcast the previous commitment transaction, which should only
5068         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5069         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5070
5071         if announce_latest {
5072                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5073         } else {
5074                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5075         }
5076         let events = nodes[2].node.get_and_clear_pending_events();
5077         let close_event = if deliver_last_raa {
5078                 assert_eq!(events.len(), 2 + 6);
5079                 events.last().clone().unwrap()
5080         } else {
5081                 assert_eq!(events.len(), 1);
5082                 events.last().clone().unwrap()
5083         };
5084         match close_event {
5085                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5086                 _ => panic!("Unexpected event"),
5087         }
5088
5089         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5090         check_closed_broadcast!(nodes[2], true);
5091         if deliver_last_raa {
5092                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5093
5094                 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();
5095                 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5096         } else {
5097                 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5098                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5099                 } else {
5100                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5101                 };
5102
5103                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5104         }
5105         check_added_monitors!(nodes[2], 3);
5106
5107         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5108         assert_eq!(cs_msgs.len(), 2);
5109         let mut a_done = false;
5110         for msg in cs_msgs {
5111                 match msg {
5112                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5113                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5114                                 // should be failed-backwards here.
5115                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5116                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5117                                         for htlc in &updates.update_fail_htlcs {
5118                                                 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 });
5119                                         }
5120                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5121                                         assert!(!a_done);
5122                                         a_done = true;
5123                                         &nodes[0]
5124                                 } else {
5125                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5126                                         for htlc in &updates.update_fail_htlcs {
5127                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5128                                         }
5129                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5130                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5131                                         &nodes[1]
5132                                 };
5133                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5134                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5135                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5136                                 if announce_latest {
5137                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5138                                         if *node_id == nodes[0].node.get_our_node_id() {
5139                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5140                                         }
5141                                 }
5142                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5143                         },
5144                         _ => panic!("Unexpected event"),
5145                 }
5146         }
5147
5148         let as_events = nodes[0].node.get_and_clear_pending_events();
5149         assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5150         let mut as_failds = HashSet::new();
5151         let mut as_updates = 0;
5152         for event in as_events.iter() {
5153                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5154                         assert!(as_failds.insert(*payment_hash));
5155                         if *payment_hash != payment_hash_2 {
5156                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5157                         } else {
5158                                 assert!(!payment_failed_permanently);
5159                         }
5160                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5161                                 as_updates += 1;
5162                         }
5163                 } else if let &Event::PaymentFailed { .. } = event {
5164                 } else { panic!("Unexpected event"); }
5165         }
5166         assert!(as_failds.contains(&payment_hash_1));
5167         assert!(as_failds.contains(&payment_hash_2));
5168         if announce_latest {
5169                 assert!(as_failds.contains(&payment_hash_3));
5170                 assert!(as_failds.contains(&payment_hash_5));
5171         }
5172         assert!(as_failds.contains(&payment_hash_6));
5173
5174         let bs_events = nodes[1].node.get_and_clear_pending_events();
5175         assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5176         let mut bs_failds = HashSet::new();
5177         let mut bs_updates = 0;
5178         for event in bs_events.iter() {
5179                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5180                         assert!(bs_failds.insert(*payment_hash));
5181                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5182                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5183                         } else {
5184                                 assert!(!payment_failed_permanently);
5185                         }
5186                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5187                                 bs_updates += 1;
5188                         }
5189                 } else if let &Event::PaymentFailed { .. } = event {
5190                 } else { panic!("Unexpected event"); }
5191         }
5192         assert!(bs_failds.contains(&payment_hash_1));
5193         assert!(bs_failds.contains(&payment_hash_2));
5194         if announce_latest {
5195                 assert!(bs_failds.contains(&payment_hash_4));
5196         }
5197         assert!(bs_failds.contains(&payment_hash_5));
5198
5199         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5200         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5201         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5202         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5203         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5204         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5205 }
5206
5207 #[test]
5208 fn test_fail_backwards_latest_remote_announce_a() {
5209         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5210 }
5211
5212 #[test]
5213 fn test_fail_backwards_latest_remote_announce_b() {
5214         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5215 }
5216
5217 #[test]
5218 fn test_fail_backwards_previous_remote_announce() {
5219         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5220         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5221         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5222 }
5223
5224 #[test]
5225 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5226         let chanmon_cfgs = create_chanmon_cfgs(2);
5227         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5228         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5229         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5230
5231         // Create some initial channels
5232         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5233
5234         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5235         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5236         assert_eq!(local_txn[0].input.len(), 1);
5237         check_spends!(local_txn[0], chan_1.3);
5238
5239         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5240         mine_transaction(&nodes[0], &local_txn[0]);
5241         check_closed_broadcast!(nodes[0], true);
5242         check_added_monitors!(nodes[0], 1);
5243         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5244         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5245
5246         let htlc_timeout = {
5247                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5248                 assert_eq!(node_txn.len(), 1);
5249                 assert_eq!(node_txn[0].input.len(), 1);
5250                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5251                 check_spends!(node_txn[0], local_txn[0]);
5252                 node_txn[0].clone()
5253         };
5254
5255         mine_transaction(&nodes[0], &htlc_timeout);
5256         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5257         expect_payment_failed!(nodes[0], our_payment_hash, false);
5258
5259         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5260         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5261         assert_eq!(spend_txn.len(), 3);
5262         check_spends!(spend_txn[0], local_txn[0]);
5263         assert_eq!(spend_txn[1].input.len(), 1);
5264         check_spends!(spend_txn[1], htlc_timeout);
5265         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5266         assert_eq!(spend_txn[2].input.len(), 2);
5267         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5268         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5269                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5270 }
5271
5272 #[test]
5273 fn test_key_derivation_params() {
5274         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5275         // manager rotation to test that `channel_keys_id` returned in
5276         // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5277         // then derive a `delayed_payment_key`.
5278
5279         let chanmon_cfgs = create_chanmon_cfgs(3);
5280
5281         // We manually create the node configuration to backup the seed.
5282         let seed = [42; 32];
5283         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5284         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);
5285         let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5286         let scorer = Mutex::new(test_utils::TestScorer::new());
5287         let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5288         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)) };
5289         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5290         node_cfgs.remove(0);
5291         node_cfgs.insert(0, node);
5292
5293         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5294         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5295
5296         // Create some initial channels
5297         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5298         // for node 0
5299         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5300         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5301         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5302
5303         // Ensure all nodes are at the same height
5304         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5305         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5306         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5307         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5308
5309         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5310         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5311         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5312         assert_eq!(local_txn_1[0].input.len(), 1);
5313         check_spends!(local_txn_1[0], chan_1.3);
5314
5315         // We check funding pubkey are unique
5316         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]));
5317         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]));
5318         if from_0_funding_key_0 == from_1_funding_key_0
5319             || from_0_funding_key_0 == from_1_funding_key_1
5320             || from_0_funding_key_1 == from_1_funding_key_0
5321             || from_0_funding_key_1 == from_1_funding_key_1 {
5322                 panic!("Funding pubkeys aren't unique");
5323         }
5324
5325         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5326         mine_transaction(&nodes[0], &local_txn_1[0]);
5327         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5328         check_closed_broadcast!(nodes[0], true);
5329         check_added_monitors!(nodes[0], 1);
5330         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5331
5332         let htlc_timeout = {
5333                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5334                 assert_eq!(node_txn.len(), 1);
5335                 assert_eq!(node_txn[0].input.len(), 1);
5336                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5337                 check_spends!(node_txn[0], local_txn_1[0]);
5338                 node_txn[0].clone()
5339         };
5340
5341         mine_transaction(&nodes[0], &htlc_timeout);
5342         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5343         expect_payment_failed!(nodes[0], our_payment_hash, false);
5344
5345         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5346         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5347         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5348         assert_eq!(spend_txn.len(), 3);
5349         check_spends!(spend_txn[0], local_txn_1[0]);
5350         assert_eq!(spend_txn[1].input.len(), 1);
5351         check_spends!(spend_txn[1], htlc_timeout);
5352         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5353         assert_eq!(spend_txn[2].input.len(), 2);
5354         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5355         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5356                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5357 }
5358
5359 #[test]
5360 fn test_static_output_closing_tx() {
5361         let chanmon_cfgs = create_chanmon_cfgs(2);
5362         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5363         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5364         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5365
5366         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5367
5368         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5369         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5370
5371         mine_transaction(&nodes[0], &closing_tx);
5372         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5373         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5374
5375         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5376         assert_eq!(spend_txn.len(), 1);
5377         check_spends!(spend_txn[0], closing_tx);
5378
5379         mine_transaction(&nodes[1], &closing_tx);
5380         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5381         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5382
5383         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5384         assert_eq!(spend_txn.len(), 1);
5385         check_spends!(spend_txn[0], closing_tx);
5386 }
5387
5388 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5389         let chanmon_cfgs = create_chanmon_cfgs(2);
5390         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5391         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5392         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5393         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5394
5395         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5396
5397         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5398         // present in B's local commitment transaction, but none of A's commitment transactions.
5399         nodes[1].node.claim_funds(payment_preimage);
5400         check_added_monitors!(nodes[1], 1);
5401         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5402
5403         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5404         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5405         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5406
5407         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5408         check_added_monitors!(nodes[0], 1);
5409         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5410         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5411         check_added_monitors!(nodes[1], 1);
5412
5413         let starting_block = nodes[1].best_block_info();
5414         let mut block = Block {
5415                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5416                 txdata: vec![],
5417         };
5418         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5419                 connect_block(&nodes[1], &block);
5420                 block.header.prev_blockhash = block.block_hash();
5421         }
5422         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5423         check_closed_broadcast!(nodes[1], true);
5424         check_added_monitors!(nodes[1], 1);
5425         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5426 }
5427
5428 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5429         let chanmon_cfgs = create_chanmon_cfgs(2);
5430         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5431         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5432         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5433         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5434
5435         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5436         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
5437         check_added_monitors!(nodes[0], 1);
5438
5439         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5440
5441         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5442         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5443         // to "time out" the HTLC.
5444
5445         let starting_block = nodes[1].best_block_info();
5446         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5447
5448         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5449                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5450                 header.prev_blockhash = header.block_hash();
5451         }
5452         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5453         check_closed_broadcast!(nodes[0], true);
5454         check_added_monitors!(nodes[0], 1);
5455         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5456 }
5457
5458 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5459         let chanmon_cfgs = create_chanmon_cfgs(3);
5460         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5461         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5462         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5463         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5464
5465         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5466         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5467         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5468         // actually revoked.
5469         let htlc_value = if use_dust { 50000 } else { 3000000 };
5470         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5471         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5472         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5473         check_added_monitors!(nodes[1], 1);
5474
5475         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5476         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5477         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5478         check_added_monitors!(nodes[0], 1);
5479         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5480         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5481         check_added_monitors!(nodes[1], 1);
5482         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5483         check_added_monitors!(nodes[1], 1);
5484         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5485
5486         if check_revoke_no_close {
5487                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5488                 check_added_monitors!(nodes[0], 1);
5489         }
5490
5491         let starting_block = nodes[1].best_block_info();
5492         let mut block = Block {
5493                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5494                 txdata: vec![],
5495         };
5496         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5497                 connect_block(&nodes[0], &block);
5498                 block.header.prev_blockhash = block.block_hash();
5499         }
5500         if !check_revoke_no_close {
5501                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5502                 check_closed_broadcast!(nodes[0], true);
5503                 check_added_monitors!(nodes[0], 1);
5504                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5505         } else {
5506                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5507         }
5508 }
5509
5510 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5511 // There are only a few cases to test here:
5512 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5513 //    broadcastable commitment transactions result in channel closure,
5514 //  * its included in an unrevoked-but-previous remote commitment transaction,
5515 //  * its included in the latest remote or local commitment transactions.
5516 // We test each of the three possible commitment transactions individually and use both dust and
5517 // non-dust HTLCs.
5518 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5519 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5520 // tested for at least one of the cases in other tests.
5521 #[test]
5522 fn htlc_claim_single_commitment_only_a() {
5523         do_htlc_claim_local_commitment_only(true);
5524         do_htlc_claim_local_commitment_only(false);
5525
5526         do_htlc_claim_current_remote_commitment_only(true);
5527         do_htlc_claim_current_remote_commitment_only(false);
5528 }
5529
5530 #[test]
5531 fn htlc_claim_single_commitment_only_b() {
5532         do_htlc_claim_previous_remote_commitment_only(true, false);
5533         do_htlc_claim_previous_remote_commitment_only(false, false);
5534         do_htlc_claim_previous_remote_commitment_only(true, true);
5535         do_htlc_claim_previous_remote_commitment_only(false, true);
5536 }
5537
5538 #[test]
5539 #[should_panic]
5540 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5541         let chanmon_cfgs = create_chanmon_cfgs(2);
5542         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5543         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5544         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5545         // Force duplicate randomness for every get-random call
5546         for node in nodes.iter() {
5547                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5548         }
5549
5550         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5551         let channel_value_satoshis=10000;
5552         let push_msat=10001;
5553         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5554         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5555         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5556         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5557
5558         // Create a second channel with the same random values. This used to panic due to a colliding
5559         // channel_id, but now panics due to a colliding outbound SCID alias.
5560         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5561 }
5562
5563 #[test]
5564 fn bolt2_open_channel_sending_node_checks_part2() {
5565         let chanmon_cfgs = create_chanmon_cfgs(2);
5566         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5567         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5568         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5569
5570         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5571         let channel_value_satoshis=2^24;
5572         let push_msat=10001;
5573         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5574
5575         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5576         let channel_value_satoshis=10000;
5577         // Test when push_msat is equal to 1000 * funding_satoshis.
5578         let push_msat=1000*channel_value_satoshis+1;
5579         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5580
5581         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5582         let channel_value_satoshis=10000;
5583         let push_msat=10001;
5584         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
5585         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5586         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5587
5588         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5589         // 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
5590         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5591
5592         // 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.
5593         assert!(BREAKDOWN_TIMEOUT>0);
5594         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5595
5596         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5597         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5598         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5599
5600         // 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.
5601         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5602         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5603         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5604         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5605         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5606 }
5607
5608 #[test]
5609 fn bolt2_open_channel_sane_dust_limit() {
5610         let chanmon_cfgs = create_chanmon_cfgs(2);
5611         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5612         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5613         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5614
5615         let channel_value_satoshis=1000000;
5616         let push_msat=10001;
5617         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5618         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5619         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5620         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5621
5622         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5623         let events = nodes[1].node.get_and_clear_pending_msg_events();
5624         let err_msg = match events[0] {
5625                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5626                         msg.clone()
5627                 },
5628                 _ => panic!("Unexpected event"),
5629         };
5630         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5631 }
5632
5633 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5634 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5635 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5636 // is no longer affordable once it's freed.
5637 #[test]
5638 fn test_fail_holding_cell_htlc_upon_free() {
5639         let chanmon_cfgs = create_chanmon_cfgs(2);
5640         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5641         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5642         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5643         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5644
5645         // First nodes[0] generates an update_fee, setting the channel's
5646         // pending_update_fee.
5647         {
5648                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5649                 *feerate_lock += 20;
5650         }
5651         nodes[0].node.timer_tick_occurred();
5652         check_added_monitors!(nodes[0], 1);
5653
5654         let events = nodes[0].node.get_and_clear_pending_msg_events();
5655         assert_eq!(events.len(), 1);
5656         let (update_msg, commitment_signed) = match events[0] {
5657                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5658                         (update_fee.as_ref(), commitment_signed)
5659                 },
5660                 _ => panic!("Unexpected event"),
5661         };
5662
5663         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5664
5665         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5666         let channel_reserve = chan_stat.channel_reserve_msat;
5667         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5668         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5669
5670         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5671         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5672         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5673
5674         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5675         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5676         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5677         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5678
5679         // Flush the pending fee update.
5680         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5681         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5682         check_added_monitors!(nodes[1], 1);
5683         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5684         check_added_monitors!(nodes[0], 1);
5685
5686         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5687         // HTLC, but now that the fee has been raised the payment will now fail, causing
5688         // us to surface its failure to the user.
5689         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5690         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5691         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);
5692         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 {}",
5693                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5694         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5695
5696         // Check that the payment failed to be sent out.
5697         let events = nodes[0].node.get_and_clear_pending_events();
5698         assert_eq!(events.len(), 2);
5699         match &events[0] {
5700                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5701                         assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5702                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5703                         assert_eq!(*payment_failed_permanently, false);
5704                         assert_eq!(*short_channel_id, Some(route.paths[0][0].short_channel_id));
5705                 },
5706                 _ => panic!("Unexpected event"),
5707         }
5708         match &events[1] {
5709                 &Event::PaymentFailed { ref payment_hash, .. } => {
5710                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5711                 },
5712                 _ => panic!("Unexpected event"),
5713         }
5714 }
5715
5716 // Test that if multiple HTLCs are released from the holding cell and one is
5717 // valid but the other is no longer valid upon release, the valid HTLC can be
5718 // successfully completed while the other one fails as expected.
5719 #[test]
5720 fn test_free_and_fail_holding_cell_htlcs() {
5721         let chanmon_cfgs = create_chanmon_cfgs(2);
5722         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5723         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5724         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5725         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5726
5727         // First nodes[0] generates an update_fee, setting the channel's
5728         // pending_update_fee.
5729         {
5730                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5731                 *feerate_lock += 200;
5732         }
5733         nodes[0].node.timer_tick_occurred();
5734         check_added_monitors!(nodes[0], 1);
5735
5736         let events = nodes[0].node.get_and_clear_pending_msg_events();
5737         assert_eq!(events.len(), 1);
5738         let (update_msg, commitment_signed) = match events[0] {
5739                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5740                         (update_fee.as_ref(), commitment_signed)
5741                 },
5742                 _ => panic!("Unexpected event"),
5743         };
5744
5745         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5746
5747         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5748         let channel_reserve = chan_stat.channel_reserve_msat;
5749         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5750         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5751
5752         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5753         let amt_1 = 20000;
5754         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
5755         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5756         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5757
5758         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5759         nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5760         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5761         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5762         let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5763         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2), payment_id_2).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 + amt_2);
5766
5767         // Flush the pending fee update.
5768         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5769         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5770         check_added_monitors!(nodes[1], 1);
5771         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5772         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5773         check_added_monitors!(nodes[0], 2);
5774
5775         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5776         // but now that the fee has been raised the second payment will now fail, causing us
5777         // to surface its failure to the user. The first payment should succeed.
5778         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5779         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5780         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);
5781         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 {}",
5782                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5783         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5784
5785         // Check that the second payment failed to be sent out.
5786         let events = nodes[0].node.get_and_clear_pending_events();
5787         assert_eq!(events.len(), 2);
5788         match &events[0] {
5789                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5790                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5791                         assert_eq!(payment_hash_2.clone(), *payment_hash);
5792                         assert_eq!(*payment_failed_permanently, false);
5793                         assert_eq!(*short_channel_id, Some(route_2.paths[0][0].short_channel_id));
5794                 },
5795                 _ => panic!("Unexpected event"),
5796         }
5797         match &events[1] {
5798                 &Event::PaymentFailed { ref payment_hash, .. } => {
5799                         assert_eq!(payment_hash_2.clone(), *payment_hash);
5800                 },
5801                 _ => panic!("Unexpected event"),
5802         }
5803
5804         // Complete the first payment and the RAA from the fee update.
5805         let (payment_event, send_raa_event) = {
5806                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5807                 assert_eq!(msgs.len(), 2);
5808                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5809         };
5810         let raa = match send_raa_event {
5811                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5812                 _ => panic!("Unexpected event"),
5813         };
5814         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5815         check_added_monitors!(nodes[1], 1);
5816         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5817         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5818         let events = nodes[1].node.get_and_clear_pending_events();
5819         assert_eq!(events.len(), 1);
5820         match events[0] {
5821                 Event::PendingHTLCsForwardable { .. } => {},
5822                 _ => panic!("Unexpected event"),
5823         }
5824         nodes[1].node.process_pending_htlc_forwards();
5825         let events = nodes[1].node.get_and_clear_pending_events();
5826         assert_eq!(events.len(), 1);
5827         match events[0] {
5828                 Event::PaymentClaimable { .. } => {},
5829                 _ => panic!("Unexpected event"),
5830         }
5831         nodes[1].node.claim_funds(payment_preimage_1);
5832         check_added_monitors!(nodes[1], 1);
5833         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5834
5835         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5836         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5837         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5838         expect_payment_sent!(nodes[0], payment_preimage_1);
5839 }
5840
5841 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
5842 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
5843 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
5844 // once it's freed.
5845 #[test]
5846 fn test_fail_holding_cell_htlc_upon_free_multihop() {
5847         let chanmon_cfgs = create_chanmon_cfgs(3);
5848         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5849         // When this test was written, the default base fee floated based on the HTLC count.
5850         // It is now fixed, so we simply set the fee to the expected value here.
5851         let mut config = test_default_channel_config();
5852         config.channel_config.forwarding_fee_base_msat = 196;
5853         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5854         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5855         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5856         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
5857
5858         // First nodes[1] generates an update_fee, setting the channel's
5859         // pending_update_fee.
5860         {
5861                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
5862                 *feerate_lock += 20;
5863         }
5864         nodes[1].node.timer_tick_occurred();
5865         check_added_monitors!(nodes[1], 1);
5866
5867         let events = nodes[1].node.get_and_clear_pending_msg_events();
5868         assert_eq!(events.len(), 1);
5869         let (update_msg, commitment_signed) = match events[0] {
5870                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5871                         (update_fee.as_ref(), commitment_signed)
5872                 },
5873                 _ => panic!("Unexpected event"),
5874         };
5875
5876         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
5877
5878         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
5879         let channel_reserve = chan_stat.channel_reserve_msat;
5880         let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
5881         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_0_1.2);
5882
5883         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5884         let feemsat = 239;
5885         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
5886         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
5887         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
5888         let payment_event = {
5889                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5890                 check_added_monitors!(nodes[0], 1);
5891
5892                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5893                 assert_eq!(events.len(), 1);
5894
5895                 SendEvent::from_event(events.remove(0))
5896         };
5897         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5898         check_added_monitors!(nodes[1], 0);
5899         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5900         expect_pending_htlcs_forwardable!(nodes[1]);
5901
5902         chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
5903         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5904
5905         // Flush the pending fee update.
5906         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
5907         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5908         check_added_monitors!(nodes[2], 1);
5909         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
5910         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
5911         check_added_monitors!(nodes[1], 2);
5912
5913         // A final RAA message is generated to finalize the fee update.
5914         let events = nodes[1].node.get_and_clear_pending_msg_events();
5915         assert_eq!(events.len(), 1);
5916
5917         let raa_msg = match &events[0] {
5918                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
5919                         msg.clone()
5920                 },
5921                 _ => panic!("Unexpected event"),
5922         };
5923
5924         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
5925         check_added_monitors!(nodes[2], 1);
5926         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
5927
5928         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
5929         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
5930         assert_eq!(process_htlc_forwards_event.len(), 2);
5931         match &process_htlc_forwards_event[0] {
5932                 &Event::PendingHTLCsForwardable { .. } => {},
5933                 _ => panic!("Unexpected event"),
5934         }
5935
5936         // In response, we call ChannelManager's process_pending_htlc_forwards
5937         nodes[1].node.process_pending_htlc_forwards();
5938         check_added_monitors!(nodes[1], 1);
5939
5940         // This causes the HTLC to be failed backwards.
5941         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
5942         assert_eq!(fail_event.len(), 1);
5943         let (fail_msg, commitment_signed) = match &fail_event[0] {
5944                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
5945                         assert_eq!(updates.update_add_htlcs.len(), 0);
5946                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
5947                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
5948                         assert_eq!(updates.update_fail_htlcs.len(), 1);
5949                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
5950                 },
5951                 _ => panic!("Unexpected event"),
5952         };
5953
5954         // Pass the failure messages back to nodes[0].
5955         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5956         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5957
5958         // Complete the HTLC failure+removal process.
5959         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5960         check_added_monitors!(nodes[0], 1);
5961         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5962         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
5963         check_added_monitors!(nodes[1], 2);
5964         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
5965         assert_eq!(final_raa_event.len(), 1);
5966         let raa = match &final_raa_event[0] {
5967                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
5968                 _ => panic!("Unexpected event"),
5969         };
5970         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
5971         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
5972         check_added_monitors!(nodes[0], 1);
5973 }
5974
5975 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
5976 // 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.
5977 //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.
5978
5979 #[test]
5980 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
5981         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
5982         let chanmon_cfgs = create_chanmon_cfgs(2);
5983         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5984         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5985         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5986         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5987
5988         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
5989         route.paths[0][0].fee_msat = 100;
5990
5991         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 },
5992                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
5993         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5994         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send less than their minimum HTLC value", 1);
5995 }
5996
5997 #[test]
5998 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
5999         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6000         let chanmon_cfgs = create_chanmon_cfgs(2);
6001         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6002         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6003         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6004         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6005
6006         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6007         route.paths[0][0].fee_msat = 0;
6008         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 },
6009                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6010
6011         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6012         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6013 }
6014
6015 #[test]
6016 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6017         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6018         let chanmon_cfgs = create_chanmon_cfgs(2);
6019         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6020         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6021         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6022         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6023
6024         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6025         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6026         check_added_monitors!(nodes[0], 1);
6027         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6028         updates.update_add_htlcs[0].amount_msat = 0;
6029
6030         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6031         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6032         check_closed_broadcast!(nodes[1], true).unwrap();
6033         check_added_monitors!(nodes[1], 1);
6034         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6035 }
6036
6037 #[test]
6038 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6039         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6040         //It is enforced when constructing a route.
6041         let chanmon_cfgs = create_chanmon_cfgs(2);
6042         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6043         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6044         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6045         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6046
6047         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6048                 .with_features(nodes[1].node.invoice_features());
6049         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6050         route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6051         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 },
6052                 assert_eq!(err, &"Channel CLTV overflowed?"));
6053 }
6054
6055 #[test]
6056 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6057         //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.
6058         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6059         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6060         let chanmon_cfgs = create_chanmon_cfgs(2);
6061         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6062         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6063         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6064         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6065         let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6066                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6067
6068         for i in 0..max_accepted_htlcs {
6069                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6070                 let payment_event = {
6071                         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6072                         check_added_monitors!(nodes[0], 1);
6073
6074                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6075                         assert_eq!(events.len(), 1);
6076                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6077                                 assert_eq!(htlcs[0].htlc_id, i);
6078                         } else {
6079                                 assert!(false);
6080                         }
6081                         SendEvent::from_event(events.remove(0))
6082                 };
6083                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6084                 check_added_monitors!(nodes[1], 0);
6085                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6086
6087                 expect_pending_htlcs_forwardable!(nodes[1]);
6088                 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6089         }
6090         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6091         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 },
6092                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6093
6094         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6095         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
6096 }
6097
6098 #[test]
6099 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6100         //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.
6101         let chanmon_cfgs = create_chanmon_cfgs(2);
6102         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6103         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6104         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6105         let channel_value = 100000;
6106         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6107         let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6108
6109         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6110
6111         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6112         // Manually create a route over our max in flight (which our router normally automatically
6113         // limits us to.
6114         route.paths[0][0].fee_msat =  max_in_flight + 1;
6115         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 },
6116                 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)));
6117
6118         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6119         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);
6120
6121         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6122 }
6123
6124 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6125 #[test]
6126 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6127         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6128         let chanmon_cfgs = create_chanmon_cfgs(2);
6129         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6130         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6131         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6132         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6133         let htlc_minimum_msat: u64;
6134         {
6135                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6136                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6137                 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6138                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6139         }
6140
6141         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6142         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6143         check_added_monitors!(nodes[0], 1);
6144         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6145         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6146         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6147         assert!(nodes[1].node.list_channels().is_empty());
6148         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6149         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()));
6150         check_added_monitors!(nodes[1], 1);
6151         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6152 }
6153
6154 #[test]
6155 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6156         //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
6157         let chanmon_cfgs = create_chanmon_cfgs(2);
6158         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6159         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6160         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6161         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6162
6163         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6164         let channel_reserve = chan_stat.channel_reserve_msat;
6165         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6166         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
6167         // The 2* and +1 are for the fee spike reserve.
6168         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6169
6170         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6171         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6172         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6173         check_added_monitors!(nodes[0], 1);
6174         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6175
6176         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6177         // at this time channel-initiatee receivers are not required to enforce that senders
6178         // respect the fee_spike_reserve.
6179         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6180         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6181
6182         assert!(nodes[1].node.list_channels().is_empty());
6183         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6184         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6185         check_added_monitors!(nodes[1], 1);
6186         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6187 }
6188
6189 #[test]
6190 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6191         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6192         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6193         let chanmon_cfgs = create_chanmon_cfgs(2);
6194         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6195         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6196         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6197         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6198
6199         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6200         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6201         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6202         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6203         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6204         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6205
6206         let mut msg = msgs::UpdateAddHTLC {
6207                 channel_id: chan.2,
6208                 htlc_id: 0,
6209                 amount_msat: 1000,
6210                 payment_hash: our_payment_hash,
6211                 cltv_expiry: htlc_cltv,
6212                 onion_routing_packet: onion_packet.clone(),
6213         };
6214
6215         for i in 0..super::channel::OUR_MAX_HTLCS {
6216                 msg.htlc_id = i as u64;
6217                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6218         }
6219         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6220         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6221
6222         assert!(nodes[1].node.list_channels().is_empty());
6223         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6224         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6225         check_added_monitors!(nodes[1], 1);
6226         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6227 }
6228
6229 #[test]
6230 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6231         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6232         let chanmon_cfgs = create_chanmon_cfgs(2);
6233         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6234         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6235         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6236         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6237
6238         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6239         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6240         check_added_monitors!(nodes[0], 1);
6241         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6242         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;
6243         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6244
6245         assert!(nodes[1].node.list_channels().is_empty());
6246         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6247         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6248         check_added_monitors!(nodes[1], 1);
6249         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6250 }
6251
6252 #[test]
6253 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6254         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6255         let chanmon_cfgs = create_chanmon_cfgs(2);
6256         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6257         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6258         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6259
6260         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6261         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6262         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6263         check_added_monitors!(nodes[0], 1);
6264         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6265         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6266         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6267
6268         assert!(nodes[1].node.list_channels().is_empty());
6269         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6270         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6271         check_added_monitors!(nodes[1], 1);
6272         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6273 }
6274
6275 #[test]
6276 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6277         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6278         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6279         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6280         let chanmon_cfgs = create_chanmon_cfgs(2);
6281         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6282         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6283         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6284
6285         create_announced_chan_between_nodes(&nodes, 0, 1);
6286         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6287         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6288         check_added_monitors!(nodes[0], 1);
6289         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6290         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6291
6292         //Disconnect and Reconnect
6293         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6294         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6295         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();
6296         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6297         assert_eq!(reestablish_1.len(), 1);
6298         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();
6299         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6300         assert_eq!(reestablish_2.len(), 1);
6301         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6302         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6303         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6304         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6305
6306         //Resend HTLC
6307         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6308         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6309         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6310         check_added_monitors!(nodes[1], 1);
6311         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6312
6313         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6314
6315         assert!(nodes[1].node.list_channels().is_empty());
6316         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6317         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6318         check_added_monitors!(nodes[1], 1);
6319         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6320 }
6321
6322 #[test]
6323 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6324         //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.
6325
6326         let chanmon_cfgs = create_chanmon_cfgs(2);
6327         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6328         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6329         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6330         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6331         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6332         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6333
6334         check_added_monitors!(nodes[0], 1);
6335         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6336         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6337
6338         let update_msg = msgs::UpdateFulfillHTLC{
6339                 channel_id: chan.2,
6340                 htlc_id: 0,
6341                 payment_preimage: our_payment_preimage,
6342         };
6343
6344         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6345
6346         assert!(nodes[0].node.list_channels().is_empty());
6347         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6348         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()));
6349         check_added_monitors!(nodes[0], 1);
6350         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6351 }
6352
6353 #[test]
6354 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6355         //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.
6356
6357         let chanmon_cfgs = create_chanmon_cfgs(2);
6358         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6359         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6360         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6361         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6362
6363         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6364         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6365         check_added_monitors!(nodes[0], 1);
6366         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6367         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6368
6369         let update_msg = msgs::UpdateFailHTLC{
6370                 channel_id: chan.2,
6371                 htlc_id: 0,
6372                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6373         };
6374
6375         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6376
6377         assert!(nodes[0].node.list_channels().is_empty());
6378         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6379         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()));
6380         check_added_monitors!(nodes[0], 1);
6381         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6382 }
6383
6384 #[test]
6385 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6386         //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.
6387
6388         let chanmon_cfgs = create_chanmon_cfgs(2);
6389         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6390         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6391         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6392         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6393
6394         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6395         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6396         check_added_monitors!(nodes[0], 1);
6397         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6398         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6399         let update_msg = msgs::UpdateFailMalformedHTLC{
6400                 channel_id: chan.2,
6401                 htlc_id: 0,
6402                 sha256_of_onion: [1; 32],
6403                 failure_code: 0x8000,
6404         };
6405
6406         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6407
6408         assert!(nodes[0].node.list_channels().is_empty());
6409         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6410         assert!(regex::Regex::new(r"Remote tried to fulfill/fail HTLC \(\d+\) before it had been committed").unwrap().is_match(err_msg.data.as_str()));
6411         check_added_monitors!(nodes[0], 1);
6412         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6413 }
6414
6415 #[test]
6416 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6417         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6418
6419         let chanmon_cfgs = create_chanmon_cfgs(2);
6420         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6421         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6422         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6423         create_announced_chan_between_nodes(&nodes, 0, 1);
6424
6425         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6426
6427         nodes[1].node.claim_funds(our_payment_preimage);
6428         check_added_monitors!(nodes[1], 1);
6429         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6430
6431         let events = nodes[1].node.get_and_clear_pending_msg_events();
6432         assert_eq!(events.len(), 1);
6433         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6434                 match events[0] {
6435                         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, .. } } => {
6436                                 assert!(update_add_htlcs.is_empty());
6437                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6438                                 assert!(update_fail_htlcs.is_empty());
6439                                 assert!(update_fail_malformed_htlcs.is_empty());
6440                                 assert!(update_fee.is_none());
6441                                 update_fulfill_htlcs[0].clone()
6442                         },
6443                         _ => panic!("Unexpected event"),
6444                 }
6445         };
6446
6447         update_fulfill_msg.htlc_id = 1;
6448
6449         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6450
6451         assert!(nodes[0].node.list_channels().is_empty());
6452         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6453         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6454         check_added_monitors!(nodes[0], 1);
6455         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6456 }
6457
6458 #[test]
6459 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6460         //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.
6461
6462         let chanmon_cfgs = create_chanmon_cfgs(2);
6463         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6464         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6465         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6466         create_announced_chan_between_nodes(&nodes, 0, 1);
6467
6468         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6469
6470         nodes[1].node.claim_funds(our_payment_preimage);
6471         check_added_monitors!(nodes[1], 1);
6472         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6473
6474         let events = nodes[1].node.get_and_clear_pending_msg_events();
6475         assert_eq!(events.len(), 1);
6476         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6477                 match events[0] {
6478                         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, .. } } => {
6479                                 assert!(update_add_htlcs.is_empty());
6480                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6481                                 assert!(update_fail_htlcs.is_empty());
6482                                 assert!(update_fail_malformed_htlcs.is_empty());
6483                                 assert!(update_fee.is_none());
6484                                 update_fulfill_htlcs[0].clone()
6485                         },
6486                         _ => panic!("Unexpected event"),
6487                 }
6488         };
6489
6490         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6491
6492         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6493
6494         assert!(nodes[0].node.list_channels().is_empty());
6495         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6496         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6497         check_added_monitors!(nodes[0], 1);
6498         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6499 }
6500
6501 #[test]
6502 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6503         //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.
6504
6505         let chanmon_cfgs = create_chanmon_cfgs(2);
6506         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6507         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6508         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6509         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6510
6511         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6512         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6513         check_added_monitors!(nodes[0], 1);
6514
6515         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6516         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6517
6518         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6519         check_added_monitors!(nodes[1], 0);
6520         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6521
6522         let events = nodes[1].node.get_and_clear_pending_msg_events();
6523
6524         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6525                 match events[0] {
6526                         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, .. } } => {
6527                                 assert!(update_add_htlcs.is_empty());
6528                                 assert!(update_fulfill_htlcs.is_empty());
6529                                 assert!(update_fail_htlcs.is_empty());
6530                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6531                                 assert!(update_fee.is_none());
6532                                 update_fail_malformed_htlcs[0].clone()
6533                         },
6534                         _ => panic!("Unexpected event"),
6535                 }
6536         };
6537         update_msg.failure_code &= !0x8000;
6538         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6539
6540         assert!(nodes[0].node.list_channels().is_empty());
6541         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6542         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6543         check_added_monitors!(nodes[0], 1);
6544         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6545 }
6546
6547 #[test]
6548 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6549         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6550         //    * 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.
6551
6552         let chanmon_cfgs = create_chanmon_cfgs(3);
6553         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6554         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6555         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6556         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6557         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6558
6559         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6560
6561         //First hop
6562         let mut payment_event = {
6563                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6564                 check_added_monitors!(nodes[0], 1);
6565                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6566                 assert_eq!(events.len(), 1);
6567                 SendEvent::from_event(events.remove(0))
6568         };
6569         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6570         check_added_monitors!(nodes[1], 0);
6571         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6572         expect_pending_htlcs_forwardable!(nodes[1]);
6573         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6574         assert_eq!(events_2.len(), 1);
6575         check_added_monitors!(nodes[1], 1);
6576         payment_event = SendEvent::from_event(events_2.remove(0));
6577         assert_eq!(payment_event.msgs.len(), 1);
6578
6579         //Second Hop
6580         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6581         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6582         check_added_monitors!(nodes[2], 0);
6583         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6584
6585         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6586         assert_eq!(events_3.len(), 1);
6587         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6588                 match events_3[0] {
6589                         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 } } => {
6590                                 assert!(update_add_htlcs.is_empty());
6591                                 assert!(update_fulfill_htlcs.is_empty());
6592                                 assert!(update_fail_htlcs.is_empty());
6593                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6594                                 assert!(update_fee.is_none());
6595                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6596                         },
6597                         _ => panic!("Unexpected event"),
6598                 }
6599         };
6600
6601         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6602
6603         check_added_monitors!(nodes[1], 0);
6604         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6605         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 }]);
6606         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6607         assert_eq!(events_4.len(), 1);
6608
6609         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6610         match events_4[0] {
6611                 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, .. } } => {
6612                         assert!(update_add_htlcs.is_empty());
6613                         assert!(update_fulfill_htlcs.is_empty());
6614                         assert_eq!(update_fail_htlcs.len(), 1);
6615                         assert!(update_fail_malformed_htlcs.is_empty());
6616                         assert!(update_fee.is_none());
6617                 },
6618                 _ => panic!("Unexpected event"),
6619         };
6620
6621         check_added_monitors!(nodes[1], 1);
6622 }
6623
6624 #[test]
6625 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6626         let chanmon_cfgs = create_chanmon_cfgs(3);
6627         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6628         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6629         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6630         create_announced_chan_between_nodes(&nodes, 0, 1);
6631         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6632
6633         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6634
6635         // First hop
6636         let mut payment_event = {
6637                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6638                 check_added_monitors!(nodes[0], 1);
6639                 SendEvent::from_node(&nodes[0])
6640         };
6641
6642         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6643         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6644         expect_pending_htlcs_forwardable!(nodes[1]);
6645         check_added_monitors!(nodes[1], 1);
6646         payment_event = SendEvent::from_node(&nodes[1]);
6647         assert_eq!(payment_event.msgs.len(), 1);
6648
6649         // Second Hop
6650         payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6651         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6652         check_added_monitors!(nodes[2], 0);
6653         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6654
6655         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6656         assert_eq!(events_3.len(), 1);
6657         match events_3[0] {
6658                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6659                         let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6660                         // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6661                         update_msg.failure_code |= 0x2000;
6662
6663                         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6664                         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6665                 },
6666                 _ => panic!("Unexpected event"),
6667         }
6668
6669         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6670                 vec![HTLCDestination::NextHopChannel {
6671                         node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6672         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6673         assert_eq!(events_4.len(), 1);
6674         check_added_monitors!(nodes[1], 1);
6675
6676         match events_4[0] {
6677                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6678                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6679                         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6680                 },
6681                 _ => panic!("Unexpected event"),
6682         }
6683
6684         let events_5 = nodes[0].node.get_and_clear_pending_events();
6685         assert_eq!(events_5.len(), 2);
6686
6687         // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6688         // the node originating the error to its next hop.
6689         match events_5[0] {
6690                 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6691                 } => {
6692                         assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6693                         assert!(is_permanent);
6694                         assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6695                 },
6696                 _ => panic!("Unexpected event"),
6697         }
6698         match events_5[1] {
6699                 Event::PaymentFailed { payment_hash, .. } => {
6700                         assert_eq!(payment_hash, our_payment_hash);
6701                 },
6702                 _ => panic!("Unexpected event"),
6703         }
6704
6705         // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6706 }
6707
6708 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6709         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6710         // 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
6711         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6712
6713         let mut chanmon_cfgs = create_chanmon_cfgs(2);
6714         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6715         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6716         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6717         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6718         let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
6719
6720         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6721                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6722
6723         // We route 2 dust-HTLCs between A and B
6724         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6725         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6726         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6727
6728         // Cache one local commitment tx as previous
6729         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6730
6731         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6732         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6733         check_added_monitors!(nodes[1], 0);
6734         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6735         check_added_monitors!(nodes[1], 1);
6736
6737         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6738         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6739         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6740         check_added_monitors!(nodes[0], 1);
6741
6742         // Cache one local commitment tx as lastest
6743         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6744
6745         let events = nodes[0].node.get_and_clear_pending_msg_events();
6746         match events[0] {
6747                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6748                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6749                 },
6750                 _ => panic!("Unexpected event"),
6751         }
6752         match events[1] {
6753                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6754                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6755                 },
6756                 _ => panic!("Unexpected event"),
6757         }
6758
6759         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6760         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6761         if announce_latest {
6762                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6763         } else {
6764                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6765         }
6766
6767         check_closed_broadcast!(nodes[0], true);
6768         check_added_monitors!(nodes[0], 1);
6769         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6770
6771         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6772         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6773         let events = nodes[0].node.get_and_clear_pending_events();
6774         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6775         assert_eq!(events.len(), 4);
6776         let mut first_failed = false;
6777         for event in events {
6778                 match event {
6779                         Event::PaymentPathFailed { payment_hash, .. } => {
6780                                 if payment_hash == payment_hash_1 {
6781                                         assert!(!first_failed);
6782                                         first_failed = true;
6783                                 } else {
6784                                         assert_eq!(payment_hash, payment_hash_2);
6785                                 }
6786                         },
6787                         Event::PaymentFailed { .. } => {}
6788                         _ => panic!("Unexpected event"),
6789                 }
6790         }
6791 }
6792
6793 #[test]
6794 fn test_failure_delay_dust_htlc_local_commitment() {
6795         do_test_failure_delay_dust_htlc_local_commitment(true);
6796         do_test_failure_delay_dust_htlc_local_commitment(false);
6797 }
6798
6799 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6800         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6801         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6802         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6803         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6804         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6805         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6806
6807         let chanmon_cfgs = create_chanmon_cfgs(3);
6808         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6809         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6810         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6811         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6812
6813         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6814                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6815
6816         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6817         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6818
6819         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6820         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6821
6822         // We revoked bs_commitment_tx
6823         if revoked {
6824                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6825                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6826         }
6827
6828         let mut timeout_tx = Vec::new();
6829         if local {
6830                 // We fail dust-HTLC 1 by broadcast of local commitment tx
6831                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
6832                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6833                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6834                 expect_payment_failed!(nodes[0], dust_hash, false);
6835
6836                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
6837                 check_closed_broadcast!(nodes[0], true);
6838                 check_added_monitors!(nodes[0], 1);
6839                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6840                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6841                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6842                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6843                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6844                 mine_transaction(&nodes[0], &timeout_tx[0]);
6845                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6846                 expect_payment_failed!(nodes[0], non_dust_hash, false);
6847         } else {
6848                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6849                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
6850                 check_closed_broadcast!(nodes[0], true);
6851                 check_added_monitors!(nodes[0], 1);
6852                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6853                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6854
6855                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
6856                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
6857                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
6858                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
6859                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
6860                 // dust HTLC should have been failed.
6861                 expect_payment_failed!(nodes[0], dust_hash, false);
6862
6863                 if !revoked {
6864                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6865                 } else {
6866                         assert_eq!(timeout_tx[0].lock_time.0, 12);
6867                 }
6868                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
6869                 mine_transaction(&nodes[0], &timeout_tx[0]);
6870                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6871                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6872                 expect_payment_failed!(nodes[0], non_dust_hash, false);
6873         }
6874 }
6875
6876 #[test]
6877 fn test_sweep_outbound_htlc_failure_update() {
6878         do_test_sweep_outbound_htlc_failure_update(false, true);
6879         do_test_sweep_outbound_htlc_failure_update(false, false);
6880         do_test_sweep_outbound_htlc_failure_update(true, false);
6881 }
6882
6883 #[test]
6884 fn test_user_configurable_csv_delay() {
6885         // We test our channel constructors yield errors when we pass them absurd csv delay
6886
6887         let mut low_our_to_self_config = UserConfig::default();
6888         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
6889         let mut high_their_to_self_config = UserConfig::default();
6890         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
6891         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6892         let chanmon_cfgs = create_chanmon_cfgs(2);
6893         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6894         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6895         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6896
6897         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6898         if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6899                 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
6900                 &low_our_to_self_config, 0, 42)
6901         {
6902                 match error {
6903                         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())); },
6904                         _ => panic!("Unexpected event"),
6905                 }
6906         } else { assert!(false) }
6907
6908         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6909         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6910         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6911         open_channel.to_self_delay = 200;
6912         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6913                 &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,
6914                 &low_our_to_self_config, 0, &nodes[0].logger, 42)
6915         {
6916                 match error {
6917                         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()));  },
6918                         _ => panic!("Unexpected event"),
6919                 }
6920         } else { assert!(false); }
6921
6922         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6923         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6924         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()));
6925         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6926         accept_channel.to_self_delay = 200;
6927         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
6928         let reason_msg;
6929         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
6930                 match action {
6931                         &ErrorAction::SendErrorMessage { ref msg } => {
6932                                 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()));
6933                                 reason_msg = msg.data.clone();
6934                         },
6935                         _ => { panic!(); }
6936                 }
6937         } else { panic!(); }
6938         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
6939
6940         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
6941         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6942         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6943         open_channel.to_self_delay = 200;
6944         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6945                 &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,
6946                 &high_their_to_self_config, 0, &nodes[0].logger, 42)
6947         {
6948                 match error {
6949                         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())); },
6950                         _ => panic!("Unexpected event"),
6951                 }
6952         } else { assert!(false); }
6953 }
6954
6955 #[test]
6956 fn test_check_htlc_underpaying() {
6957         // Send payment through A -> B but A is maliciously
6958         // sending a probe payment (i.e less than expected value0
6959         // to B, B should refuse payment.
6960
6961         let chanmon_cfgs = create_chanmon_cfgs(2);
6962         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6963         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6964         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6965
6966         // Create some initial channels
6967         create_announced_chan_between_nodes(&nodes, 0, 1);
6968
6969         let scorer = test_utils::TestScorer::new();
6970         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
6971         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV).with_features(nodes[1].node.invoice_features());
6972         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();
6973         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
6974         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
6975         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6976         check_added_monitors!(nodes[0], 1);
6977
6978         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6979         assert_eq!(events.len(), 1);
6980         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
6981         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6982         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6983
6984         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
6985         // and then will wait a second random delay before failing the HTLC back:
6986         expect_pending_htlcs_forwardable!(nodes[1]);
6987         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
6988
6989         // Node 3 is expecting payment of 100_000 but received 10_000,
6990         // it should fail htlc like we didn't know the preimage.
6991         nodes[1].node.process_pending_htlc_forwards();
6992
6993         let events = nodes[1].node.get_and_clear_pending_msg_events();
6994         assert_eq!(events.len(), 1);
6995         let (update_fail_htlc, commitment_signed) = match events[0] {
6996                 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 } } => {
6997                         assert!(update_add_htlcs.is_empty());
6998                         assert!(update_fulfill_htlcs.is_empty());
6999                         assert_eq!(update_fail_htlcs.len(), 1);
7000                         assert!(update_fail_malformed_htlcs.is_empty());
7001                         assert!(update_fee.is_none());
7002                         (update_fail_htlcs[0].clone(), commitment_signed)
7003                 },
7004                 _ => panic!("Unexpected event"),
7005         };
7006         check_added_monitors!(nodes[1], 1);
7007
7008         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7009         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7010
7011         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7012         let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7013         expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7014         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7015 }
7016
7017 #[test]
7018 fn test_announce_disable_channels() {
7019         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7020         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7021
7022         let chanmon_cfgs = create_chanmon_cfgs(2);
7023         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7024         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7025         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7026
7027         create_announced_chan_between_nodes(&nodes, 0, 1);
7028         create_announced_chan_between_nodes(&nodes, 1, 0);
7029         create_announced_chan_between_nodes(&nodes, 0, 1);
7030
7031         // Disconnect peers
7032         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7033         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7034
7035         nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7036         nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7037         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7038         assert_eq!(msg_events.len(), 3);
7039         let mut chans_disabled = HashMap::new();
7040         for e in msg_events {
7041                 match e {
7042                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7043                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7044                                 // Check that each channel gets updated exactly once
7045                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7046                                         panic!("Generated ChannelUpdate for wrong chan!");
7047                                 }
7048                         },
7049                         _ => panic!("Unexpected event"),
7050                 }
7051         }
7052         // Reconnect peers
7053         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();
7054         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7055         assert_eq!(reestablish_1.len(), 3);
7056         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();
7057         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7058         assert_eq!(reestablish_2.len(), 3);
7059
7060         // Reestablish chan_1
7061         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7062         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7063         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7064         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7065         // Reestablish chan_2
7066         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7067         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7068         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7069         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7070         // Reestablish chan_3
7071         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7072         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7073         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7074         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7075
7076         nodes[0].node.timer_tick_occurred();
7077         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7078         nodes[0].node.timer_tick_occurred();
7079         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7080         assert_eq!(msg_events.len(), 3);
7081         for e in msg_events {
7082                 match e {
7083                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7084                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7085                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7086                                         // Each update should have a higher timestamp than the previous one, replacing
7087                                         // the old one.
7088                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7089                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7090                                 }
7091                         },
7092                         _ => panic!("Unexpected event"),
7093                 }
7094         }
7095         // Check that each channel gets updated exactly once
7096         assert!(chans_disabled.is_empty());
7097 }
7098
7099 #[test]
7100 fn test_bump_penalty_txn_on_revoked_commitment() {
7101         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7102         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7103
7104         let chanmon_cfgs = create_chanmon_cfgs(2);
7105         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7106         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7107         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7108
7109         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7110
7111         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7112         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7113                 .with_features(nodes[0].node.invoice_features());
7114         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7115         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7116
7117         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7118         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7119         assert_eq!(revoked_txn[0].output.len(), 4);
7120         assert_eq!(revoked_txn[0].input.len(), 1);
7121         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7122         let revoked_txid = revoked_txn[0].txid();
7123
7124         let mut penalty_sum = 0;
7125         for outp in revoked_txn[0].output.iter() {
7126                 if outp.script_pubkey.is_v0_p2wsh() {
7127                         penalty_sum += outp.value;
7128                 }
7129         }
7130
7131         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7132         let header_114 = connect_blocks(&nodes[1], 14);
7133
7134         // Actually revoke tx by claiming a HTLC
7135         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7136         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7137         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7138         check_added_monitors!(nodes[1], 1);
7139
7140         // One or more justice tx should have been broadcast, check it
7141         let penalty_1;
7142         let feerate_1;
7143         {
7144                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7145                 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7146                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7147                 assert_eq!(node_txn[0].output.len(), 1);
7148                 check_spends!(node_txn[0], revoked_txn[0]);
7149                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7150                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7151                 penalty_1 = node_txn[0].txid();
7152                 node_txn.clear();
7153         };
7154
7155         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7156         connect_blocks(&nodes[1], 15);
7157         let mut penalty_2 = penalty_1;
7158         let mut feerate_2 = 0;
7159         {
7160                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7161                 assert_eq!(node_txn.len(), 1);
7162                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7163                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7164                         assert_eq!(node_txn[0].output.len(), 1);
7165                         check_spends!(node_txn[0], revoked_txn[0]);
7166                         penalty_2 = node_txn[0].txid();
7167                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7168                         assert_ne!(penalty_2, penalty_1);
7169                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7170                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7171                         // Verify 25% bump heuristic
7172                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7173                         node_txn.clear();
7174                 }
7175         }
7176         assert_ne!(feerate_2, 0);
7177
7178         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7179         connect_blocks(&nodes[1], 1);
7180         let penalty_3;
7181         let mut feerate_3 = 0;
7182         {
7183                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7184                 assert_eq!(node_txn.len(), 1);
7185                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7186                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7187                         assert_eq!(node_txn[0].output.len(), 1);
7188                         check_spends!(node_txn[0], revoked_txn[0]);
7189                         penalty_3 = node_txn[0].txid();
7190                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7191                         assert_ne!(penalty_3, penalty_2);
7192                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7193                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7194                         // Verify 25% bump heuristic
7195                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7196                         node_txn.clear();
7197                 }
7198         }
7199         assert_ne!(feerate_3, 0);
7200
7201         nodes[1].node.get_and_clear_pending_events();
7202         nodes[1].node.get_and_clear_pending_msg_events();
7203 }
7204
7205 #[test]
7206 fn test_bump_penalty_txn_on_revoked_htlcs() {
7207         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7208         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7209
7210         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7211         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7212         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7213         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7214         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7215
7216         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7217         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7218         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_features(nodes[1].node.invoice_features());
7219         let scorer = test_utils::TestScorer::new();
7220         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7221         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7222                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7223         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7224         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_features(nodes[0].node.invoice_features());
7225         let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7226                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7227         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7228
7229         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7230         assert_eq!(revoked_local_txn[0].input.len(), 1);
7231         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7232
7233         // Revoke local commitment tx
7234         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7235
7236         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7237         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7238         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7239         check_closed_broadcast!(nodes[1], true);
7240         check_added_monitors!(nodes[1], 1);
7241         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7242         connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7243
7244         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
7245         assert_eq!(revoked_htlc_txn.len(), 2);
7246
7247         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7248         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7249         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7250
7251         assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7252         assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7253         assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7254         check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7255
7256         // Broadcast set of revoked txn on A
7257         let hash_128 = connect_blocks(&nodes[0], 40);
7258         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7259         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7260         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7261         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] });
7262         let events = nodes[0].node.get_and_clear_pending_events();
7263         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7264         match events.last().unwrap() {
7265                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7266                 _ => panic!("Unexpected event"),
7267         }
7268         let first;
7269         let feerate_1;
7270         let penalty_txn;
7271         {
7272                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7273                 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7274                 // Verify claim tx are spending revoked HTLC txn
7275
7276                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7277                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7278                 // which are included in the same block (they are broadcasted because we scan the
7279                 // transactions linearly and generate claims as we go, they likely should be removed in the
7280                 // future).
7281                 assert_eq!(node_txn[0].input.len(), 1);
7282                 check_spends!(node_txn[0], revoked_local_txn[0]);
7283                 assert_eq!(node_txn[1].input.len(), 1);
7284                 check_spends!(node_txn[1], revoked_local_txn[0]);
7285                 assert_eq!(node_txn[2].input.len(), 1);
7286                 check_spends!(node_txn[2], revoked_local_txn[0]);
7287
7288                 // Each of the three justice transactions claim a separate (single) output of the three
7289                 // available, which we check here:
7290                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7291                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7292                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7293
7294                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7295                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7296
7297                 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7298                 // output, checked above).
7299                 assert_eq!(node_txn[3].input.len(), 2);
7300                 assert_eq!(node_txn[3].output.len(), 1);
7301                 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7302
7303                 first = node_txn[3].txid();
7304                 // Store both feerates for later comparison
7305                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7306                 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7307                 penalty_txn = vec![node_txn[2].clone()];
7308                 node_txn.clear();
7309         }
7310
7311         // Connect one more block to see if bumped penalty are issued for HTLC txn
7312         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7313         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7314         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7315         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7316
7317         // Few more blocks to confirm penalty txn
7318         connect_blocks(&nodes[0], 4);
7319         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7320         let header_144 = connect_blocks(&nodes[0], 9);
7321         let node_txn = {
7322                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7323                 assert_eq!(node_txn.len(), 1);
7324
7325                 assert_eq!(node_txn[0].input.len(), 2);
7326                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7327                 // Verify bumped tx is different and 25% bump heuristic
7328                 assert_ne!(first, node_txn[0].txid());
7329                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7330                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7331                 assert!(feerate_2 * 100 > feerate_1 * 125);
7332                 let txn = vec![node_txn[0].clone()];
7333                 node_txn.clear();
7334                 txn
7335         };
7336         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7337         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7338         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7339         connect_blocks(&nodes[0], 20);
7340         {
7341                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7342                 // We verify than no new transaction has been broadcast because previously
7343                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7344                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7345                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7346                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7347                 // up bumped justice generation.
7348                 assert_eq!(node_txn.len(), 0);
7349                 node_txn.clear();
7350         }
7351         check_closed_broadcast!(nodes[0], true);
7352         check_added_monitors!(nodes[0], 1);
7353 }
7354
7355 #[test]
7356 fn test_bump_penalty_txn_on_remote_commitment() {
7357         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7358         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7359
7360         // Create 2 HTLCs
7361         // Provide preimage for one
7362         // Check aggregation
7363
7364         let chanmon_cfgs = create_chanmon_cfgs(2);
7365         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7366         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7367         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7368
7369         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7370         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7371         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7372
7373         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7374         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7375         assert_eq!(remote_txn[0].output.len(), 4);
7376         assert_eq!(remote_txn[0].input.len(), 1);
7377         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7378
7379         // Claim a HTLC without revocation (provide B monitor with preimage)
7380         nodes[1].node.claim_funds(payment_preimage);
7381         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7382         mine_transaction(&nodes[1], &remote_txn[0]);
7383         check_added_monitors!(nodes[1], 2);
7384         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7385
7386         // One or more claim tx should have been broadcast, check it
7387         let timeout;
7388         let preimage;
7389         let preimage_bump;
7390         let feerate_timeout;
7391         let feerate_preimage;
7392         {
7393                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7394                 // 3 transactions including:
7395                 //   preimage and timeout sweeps from remote commitment + preimage sweep bump
7396                 assert_eq!(node_txn.len(), 3);
7397                 assert_eq!(node_txn[0].input.len(), 1);
7398                 assert_eq!(node_txn[1].input.len(), 1);
7399                 assert_eq!(node_txn[2].input.len(), 1);
7400                 check_spends!(node_txn[0], remote_txn[0]);
7401                 check_spends!(node_txn[1], remote_txn[0]);
7402                 check_spends!(node_txn[2], remote_txn[0]);
7403
7404                 preimage = node_txn[0].txid();
7405                 let index = node_txn[0].input[0].previous_output.vout;
7406                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7407                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7408
7409                 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7410                         (node_txn[2].clone(), node_txn[1].clone())
7411                 } else {
7412                         (node_txn[1].clone(), node_txn[2].clone())
7413                 };
7414
7415                 preimage_bump = preimage_bump_tx;
7416                 check_spends!(preimage_bump, remote_txn[0]);
7417                 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7418
7419                 timeout = timeout_tx.txid();
7420                 let index = timeout_tx.input[0].previous_output.vout;
7421                 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7422                 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7423
7424                 node_txn.clear();
7425         };
7426         assert_ne!(feerate_timeout, 0);
7427         assert_ne!(feerate_preimage, 0);
7428
7429         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7430         connect_blocks(&nodes[1], 15);
7431         {
7432                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7433                 assert_eq!(node_txn.len(), 1);
7434                 assert_eq!(node_txn[0].input.len(), 1);
7435                 assert_eq!(preimage_bump.input.len(), 1);
7436                 check_spends!(node_txn[0], remote_txn[0]);
7437                 check_spends!(preimage_bump, remote_txn[0]);
7438
7439                 let index = preimage_bump.input[0].previous_output.vout;
7440                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7441                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7442                 assert!(new_feerate * 100 > feerate_timeout * 125);
7443                 assert_ne!(timeout, preimage_bump.txid());
7444
7445                 let index = node_txn[0].input[0].previous_output.vout;
7446                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7447                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7448                 assert!(new_feerate * 100 > feerate_preimage * 125);
7449                 assert_ne!(preimage, node_txn[0].txid());
7450
7451                 node_txn.clear();
7452         }
7453
7454         nodes[1].node.get_and_clear_pending_events();
7455         nodes[1].node.get_and_clear_pending_msg_events();
7456 }
7457
7458 #[test]
7459 fn test_counterparty_raa_skip_no_crash() {
7460         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7461         // commitment transaction, we would have happily carried on and provided them the next
7462         // commitment transaction based on one RAA forward. This would probably eventually have led to
7463         // channel closure, but it would not have resulted in funds loss. Still, our
7464         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7465         // check simply that the channel is closed in response to such an RAA, but don't check whether
7466         // we decide to punish our counterparty for revoking their funds (as we don't currently
7467         // implement that).
7468         let chanmon_cfgs = create_chanmon_cfgs(2);
7469         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7470         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7471         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7472         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7473
7474         let per_commitment_secret;
7475         let next_per_commitment_point;
7476         {
7477                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7478                 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7479                 let keys = guard.channel_by_id.get_mut(&channel_id).unwrap().get_signer();
7480
7481                 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7482
7483                 // Make signer believe we got a counterparty signature, so that it allows the revocation
7484                 keys.get_enforcement_state().last_holder_commitment -= 1;
7485                 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7486
7487                 // Must revoke without gaps
7488                 keys.get_enforcement_state().last_holder_commitment -= 1;
7489                 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7490
7491                 keys.get_enforcement_state().last_holder_commitment -= 1;
7492                 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7493                         &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7494         }
7495
7496         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7497                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7498         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7499         check_added_monitors!(nodes[1], 1);
7500         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7501 }
7502
7503 #[test]
7504 fn test_bump_txn_sanitize_tracking_maps() {
7505         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7506         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7507
7508         let chanmon_cfgs = create_chanmon_cfgs(2);
7509         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7510         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7511         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7512
7513         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7514         // Lock HTLC in both directions
7515         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7516         let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7517
7518         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7519         assert_eq!(revoked_local_txn[0].input.len(), 1);
7520         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7521
7522         // Revoke local commitment tx
7523         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7524
7525         // Broadcast set of revoked txn on A
7526         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7527         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7528         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7529
7530         mine_transaction(&nodes[0], &revoked_local_txn[0]);
7531         check_closed_broadcast!(nodes[0], true);
7532         check_added_monitors!(nodes[0], 1);
7533         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7534         let penalty_txn = {
7535                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7536                 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7537                 check_spends!(node_txn[0], revoked_local_txn[0]);
7538                 check_spends!(node_txn[1], revoked_local_txn[0]);
7539                 check_spends!(node_txn[2], revoked_local_txn[0]);
7540                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7541                 node_txn.clear();
7542                 penalty_txn
7543         };
7544         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7545         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7546         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7547         {
7548                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7549                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7550                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7551         }
7552 }
7553
7554 #[test]
7555 fn test_pending_claimed_htlc_no_balance_underflow() {
7556         // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
7557         // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
7558         let chanmon_cfgs = create_chanmon_cfgs(2);
7559         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7560         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7561         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7562         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
7563
7564         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
7565         nodes[1].node.claim_funds(payment_preimage);
7566         expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
7567         check_added_monitors!(nodes[1], 1);
7568         let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7569
7570         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
7571         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
7572         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
7573         check_added_monitors!(nodes[0], 1);
7574         let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7575
7576         // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
7577         // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
7578         // can get our balance.
7579
7580         // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
7581         // the public key of the only hop. This works around ChannelDetails not showing the
7582         // almost-claimed HTLC as available balance.
7583         let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
7584         route.payment_params = None; // This is all wrong, but unnecessary
7585         route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
7586         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
7587         nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
7588
7589         assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
7590 }
7591
7592 #[test]
7593 fn test_channel_conf_timeout() {
7594         // Tests that, for inbound channels, we give up on them if the funding transaction does not
7595         // confirm within 2016 blocks, as recommended by BOLT 2.
7596         let chanmon_cfgs = create_chanmon_cfgs(2);
7597         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7598         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7599         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7600
7601         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7602
7603         // The outbound node should wait forever for confirmation:
7604         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7605         // copied here instead of directly referencing the constant.
7606         connect_blocks(&nodes[0], 2016);
7607         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7608
7609         // The inbound node should fail the channel after exactly 2016 blocks
7610         connect_blocks(&nodes[1], 2015);
7611         check_added_monitors!(nodes[1], 0);
7612         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7613
7614         connect_blocks(&nodes[1], 1);
7615         check_added_monitors!(nodes[1], 1);
7616         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
7617         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7618         assert_eq!(close_ev.len(), 1);
7619         match close_ev[0] {
7620                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7621                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7622                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7623                 },
7624                 _ => panic!("Unexpected event"),
7625         }
7626 }
7627
7628 #[test]
7629 fn test_override_channel_config() {
7630         let chanmon_cfgs = create_chanmon_cfgs(2);
7631         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7632         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7633         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7634
7635         // Node0 initiates a channel to node1 using the override config.
7636         let mut override_config = UserConfig::default();
7637         override_config.channel_handshake_config.our_to_self_delay = 200;
7638
7639         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7640
7641         // Assert the channel created by node0 is using the override config.
7642         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7643         assert_eq!(res.channel_flags, 0);
7644         assert_eq!(res.to_self_delay, 200);
7645 }
7646
7647 #[test]
7648 fn test_override_0msat_htlc_minimum() {
7649         let mut zero_config = UserConfig::default();
7650         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7651         let chanmon_cfgs = create_chanmon_cfgs(2);
7652         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7653         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7654         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7655
7656         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7657         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7658         assert_eq!(res.htlc_minimum_msat, 1);
7659
7660         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7661         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7662         assert_eq!(res.htlc_minimum_msat, 1);
7663 }
7664
7665 #[test]
7666 fn test_channel_update_has_correct_htlc_maximum_msat() {
7667         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7668         // Bolt 7 specifies that if present `htlc_maximum_msat`:
7669         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7670         // 90% of the `channel_value`.
7671         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7672
7673         let mut config_30_percent = UserConfig::default();
7674         config_30_percent.channel_handshake_config.announced_channel = true;
7675         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7676         let mut config_50_percent = UserConfig::default();
7677         config_50_percent.channel_handshake_config.announced_channel = true;
7678         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7679         let mut config_95_percent = UserConfig::default();
7680         config_95_percent.channel_handshake_config.announced_channel = true;
7681         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7682         let mut config_100_percent = UserConfig::default();
7683         config_100_percent.channel_handshake_config.announced_channel = true;
7684         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7685
7686         let chanmon_cfgs = create_chanmon_cfgs(4);
7687         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7688         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)]);
7689         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7690
7691         let channel_value_satoshis = 100000;
7692         let channel_value_msat = channel_value_satoshis * 1000;
7693         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7694         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7695         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7696
7697         let (node_0_chan_update, node_1_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7698         let (node_2_chan_update, node_3_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7699
7700         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7701         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7702         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7703         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7704         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7705         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7706
7707         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7708         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7709         // `channel_value`.
7710         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7711         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7712         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7713         // `channel_value`.
7714         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7715 }
7716
7717 #[test]
7718 fn test_manually_accept_inbound_channel_request() {
7719         let mut manually_accept_conf = UserConfig::default();
7720         manually_accept_conf.manually_accept_inbound_channels = true;
7721         let chanmon_cfgs = create_chanmon_cfgs(2);
7722         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7723         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7724         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7725
7726         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7727         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7728
7729         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7730
7731         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7732         // accepting the inbound channel request.
7733         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7734
7735         let events = nodes[1].node.get_and_clear_pending_events();
7736         match events[0] {
7737                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7738                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7739                 }
7740                 _ => panic!("Unexpected event"),
7741         }
7742
7743         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7744         assert_eq!(accept_msg_ev.len(), 1);
7745
7746         match accept_msg_ev[0] {
7747                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7748                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7749                 }
7750                 _ => panic!("Unexpected event"),
7751         }
7752
7753         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7754
7755         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7756         assert_eq!(close_msg_ev.len(), 1);
7757
7758         let events = nodes[1].node.get_and_clear_pending_events();
7759         match events[0] {
7760                 Event::ChannelClosed { user_channel_id, .. } => {
7761                         assert_eq!(user_channel_id, 23);
7762                 }
7763                 _ => panic!("Unexpected event"),
7764         }
7765 }
7766
7767 #[test]
7768 fn test_manually_reject_inbound_channel_request() {
7769         let mut manually_accept_conf = UserConfig::default();
7770         manually_accept_conf.manually_accept_inbound_channels = true;
7771         let chanmon_cfgs = create_chanmon_cfgs(2);
7772         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7773         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7774         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7775
7776         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7777         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7778
7779         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7780
7781         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7782         // rejecting the inbound channel request.
7783         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7784
7785         let events = nodes[1].node.get_and_clear_pending_events();
7786         match events[0] {
7787                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7788                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7789                 }
7790                 _ => panic!("Unexpected event"),
7791         }
7792
7793         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7794         assert_eq!(close_msg_ev.len(), 1);
7795
7796         match close_msg_ev[0] {
7797                 MessageSendEvent::HandleError { ref node_id, .. } => {
7798                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7799                 }
7800                 _ => panic!("Unexpected event"),
7801         }
7802         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
7803 }
7804
7805 #[test]
7806 fn test_reject_funding_before_inbound_channel_accepted() {
7807         // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
7808         // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
7809         // the node operator before the counterparty sends a `FundingCreated` message. If a
7810         // `FundingCreated` message is received before the channel is accepted, it should be rejected
7811         // and the channel should be closed.
7812         let mut manually_accept_conf = UserConfig::default();
7813         manually_accept_conf.manually_accept_inbound_channels = true;
7814         let chanmon_cfgs = create_chanmon_cfgs(2);
7815         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7816         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7817         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7818
7819         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7820         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7821         let temp_channel_id = res.temporary_channel_id;
7822
7823         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7824
7825         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
7826         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7827
7828         // Clear the `Event::OpenChannelRequest` event without responding to the request.
7829         nodes[1].node.get_and_clear_pending_events();
7830
7831         // Get the `AcceptChannel` message of `nodes[1]` without calling
7832         // `ChannelManager::accept_inbound_channel`, which generates a
7833         // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
7834         // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
7835         // succeed when `nodes[0]` is passed to it.
7836         let accept_chan_msg = {
7837                 let mut node_1_per_peer_lock;
7838                 let mut node_1_peer_state_lock;
7839                 let channel =  get_channel_ref!(&nodes[1], nodes[0], node_1_per_peer_lock, node_1_peer_state_lock, temp_channel_id);
7840                 channel.get_accept_channel_message()
7841         };
7842         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
7843
7844         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
7845
7846         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
7847         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
7848
7849         // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
7850         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
7851
7852         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7853         assert_eq!(close_msg_ev.len(), 1);
7854
7855         let expected_err = "FundingCreated message received before the channel was accepted";
7856         match close_msg_ev[0] {
7857                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
7858                         assert_eq!(msg.channel_id, temp_channel_id);
7859                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7860                         assert_eq!(msg.data, expected_err);
7861                 }
7862                 _ => panic!("Unexpected event"),
7863         }
7864
7865         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
7866 }
7867
7868 #[test]
7869 fn test_can_not_accept_inbound_channel_twice() {
7870         let mut manually_accept_conf = UserConfig::default();
7871         manually_accept_conf.manually_accept_inbound_channels = true;
7872         let chanmon_cfgs = create_chanmon_cfgs(2);
7873         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7874         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7875         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7876
7877         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7878         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7879
7880         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7881
7882         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7883         // accepting the inbound channel request.
7884         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7885
7886         let events = nodes[1].node.get_and_clear_pending_events();
7887         match events[0] {
7888                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7889                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7890                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7891                         match api_res {
7892                                 Err(APIError::APIMisuseError { err }) => {
7893                                         assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
7894                                 },
7895                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7896                                 Err(_) => panic!("Unexpected Error"),
7897                         }
7898                 }
7899                 _ => panic!("Unexpected event"),
7900         }
7901
7902         // Ensure that the channel wasn't closed after attempting to accept it twice.
7903         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7904         assert_eq!(accept_msg_ev.len(), 1);
7905
7906         match accept_msg_ev[0] {
7907                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7908                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7909                 }
7910                 _ => panic!("Unexpected event"),
7911         }
7912 }
7913
7914 #[test]
7915 fn test_can_not_accept_unknown_inbound_channel() {
7916         let chanmon_cfg = create_chanmon_cfgs(2);
7917         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
7918         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
7919         let nodes = create_network(2, &node_cfg, &node_chanmgr);
7920
7921         let unknown_channel_id = [0; 32];
7922         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
7923         match api_res {
7924                 Err(APIError::ChannelUnavailable { err }) => {
7925                         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()));
7926                 },
7927                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
7928                 Err(_) => panic!("Unexpected Error"),
7929         }
7930 }
7931
7932 #[test]
7933 fn test_onion_value_mpp_set_calculation() {
7934         // Test that we use the onion value `amt_to_forward` when
7935         // calculating whether we've reached the `total_msat` of an MPP
7936         // by having a routing node forward more than `amt_to_forward`
7937         // and checking that the receiving node doesn't generate
7938         // a PaymentClaimable event too early
7939         let node_count = 4;
7940         let chanmon_cfgs = create_chanmon_cfgs(node_count);
7941         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
7942         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
7943         let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
7944
7945         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
7946         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
7947         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
7948         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
7949
7950         let total_msat = 100_000;
7951         let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
7952         let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
7953         let sample_path = route.paths.pop().unwrap();
7954
7955         let mut path_1 = sample_path.clone();
7956         path_1[0].pubkey = nodes[1].node.get_our_node_id();
7957         path_1[0].short_channel_id = chan_1_id;
7958         path_1[1].pubkey = nodes[3].node.get_our_node_id();
7959         path_1[1].short_channel_id = chan_3_id;
7960         path_1[1].fee_msat = 100_000;
7961         route.paths.push(path_1);
7962
7963         let mut path_2 = sample_path.clone();
7964         path_2[0].pubkey = nodes[2].node.get_our_node_id();
7965         path_2[0].short_channel_id = chan_2_id;
7966         path_2[1].pubkey = nodes[3].node.get_our_node_id();
7967         path_2[1].short_channel_id = chan_4_id;
7968         path_2[1].fee_msat = 1_000;
7969         route.paths.push(path_2);
7970
7971         // Send payment
7972         let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
7973         let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(our_payment_secret), payment_id, &route).unwrap();
7974         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();
7975         check_added_monitors!(nodes[0], expected_paths.len());
7976
7977         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7978         assert_eq!(events.len(), expected_paths.len());
7979
7980         // First path
7981         let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
7982         let mut payment_event = SendEvent::from_event(ev);
7983         let mut prev_node = &nodes[0];
7984
7985         for (idx, &node) in expected_paths[0].iter().enumerate() {
7986                 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
7987
7988                 if idx == 0 { // routing node
7989                         let session_priv = [3; 32];
7990                         let height = nodes[0].best_block_info().1;
7991                         let session_priv = SecretKey::from_slice(&session_priv).unwrap();
7992                         let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
7993                         let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000, &Some(our_payment_secret), height + 1, &None).unwrap();
7994                         // Edit amt_to_forward to simulate the sender having set
7995                         // the final amount and the routing node taking less fee
7996                         onion_payloads[1].amt_to_forward = 99_000;
7997                         let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
7998                         payment_event.msgs[0].onion_routing_packet = new_onion_packet;
7999                 }
8000
8001                 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8002                 check_added_monitors!(node, 0);
8003                 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8004                 expect_pending_htlcs_forwardable!(node);
8005
8006                 if idx == 0 {
8007                         let mut events_2 = node.node.get_and_clear_pending_msg_events();
8008                         assert_eq!(events_2.len(), 1);
8009                         check_added_monitors!(node, 1);
8010                         payment_event = SendEvent::from_event(events_2.remove(0));
8011                         assert_eq!(payment_event.msgs.len(), 1);
8012                 } else {
8013                         let events_2 = node.node.get_and_clear_pending_events();
8014                         assert!(events_2.is_empty());
8015                 }
8016
8017                 prev_node = node;
8018         }
8019
8020         // Second path
8021         let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8022         pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8023
8024         claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8025 }
8026
8027 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8028
8029         let routing_node_count = msat_amounts.len();
8030         let node_count = routing_node_count + 2;
8031
8032         let chanmon_cfgs = create_chanmon_cfgs(node_count);
8033         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8034         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8035         let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8036
8037         let src_idx = 0;
8038         let dst_idx = 1;
8039
8040         // Create channels for each amount
8041         let mut expected_paths = Vec::with_capacity(routing_node_count);
8042         let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8043         let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8044         for i in 0..routing_node_count {
8045                 let routing_node = 2 + i;
8046                 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8047                 src_chan_ids.push(src_chan_id);
8048                 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8049                 dst_chan_ids.push(dst_chan_id);
8050                 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8051                 expected_paths.push(path);
8052         }
8053         let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8054
8055         // Create a route for each amount
8056         let example_amount = 100000;
8057         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);
8058         let sample_path = route.paths.pop().unwrap();
8059         for i in 0..routing_node_count {
8060                 let routing_node = 2 + i;
8061                 let mut path = sample_path.clone();
8062                 path[0].pubkey = nodes[routing_node].node.get_our_node_id();
8063                 path[0].short_channel_id = src_chan_ids[i];
8064                 path[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8065                 path[1].short_channel_id = dst_chan_ids[i];
8066                 path[1].fee_msat = msat_amounts[i];
8067                 route.paths.push(path);
8068         }
8069
8070         // Send payment with manually set total_msat
8071         let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8072         let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash, Some(our_payment_secret), payment_id, &route).unwrap();
8073         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();
8074         check_added_monitors!(nodes[src_idx], expected_paths.len());
8075
8076         let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8077         assert_eq!(events.len(), expected_paths.len());
8078         let mut amount_received = 0;
8079         for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8080                 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8081
8082                 let current_path_amount = msat_amounts[path_idx];
8083                 amount_received += current_path_amount;
8084                 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8085                 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8086         }
8087
8088         claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8089 }
8090
8091 #[test]
8092 fn test_overshoot_mpp() {
8093         do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8094         do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8095 }
8096
8097 #[test]
8098 fn test_simple_mpp() {
8099         // Simple test of sending a multi-path payment.
8100         let chanmon_cfgs = create_chanmon_cfgs(4);
8101         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8102         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8103         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8104
8105         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8106         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8107         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8108         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8109
8110         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8111         let path = route.paths[0].clone();
8112         route.paths.push(path);
8113         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8114         route.paths[0][0].short_channel_id = chan_1_id;
8115         route.paths[0][1].short_channel_id = chan_3_id;
8116         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8117         route.paths[1][0].short_channel_id = chan_2_id;
8118         route.paths[1][1].short_channel_id = chan_4_id;
8119         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8120         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8121 }
8122
8123 #[test]
8124 fn test_preimage_storage() {
8125         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8126         let chanmon_cfgs = create_chanmon_cfgs(2);
8127         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8128         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8129         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8130
8131         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8132
8133         {
8134                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8135                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8136                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
8137                 check_added_monitors!(nodes[0], 1);
8138                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8139                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8140                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8141                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8142         }
8143         // Note that after leaving the above scope we have no knowledge of any arguments or return
8144         // values from previous calls.
8145         expect_pending_htlcs_forwardable!(nodes[1]);
8146         let events = nodes[1].node.get_and_clear_pending_events();
8147         assert_eq!(events.len(), 1);
8148         match events[0] {
8149                 Event::PaymentClaimable { ref purpose, .. } => {
8150                         match &purpose {
8151                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8152                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8153                                 },
8154                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8155                         }
8156                 },
8157                 _ => panic!("Unexpected event"),
8158         }
8159 }
8160
8161 #[test]
8162 #[allow(deprecated)]
8163 fn test_secret_timeout() {
8164         // Simple test of payment secret storage time outs. After
8165         // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8166         let chanmon_cfgs = create_chanmon_cfgs(2);
8167         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8168         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8169         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8170
8171         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8172
8173         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8174
8175         // We should fail to register the same payment hash twice, at least until we've connected a
8176         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8177         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8178                 assert_eq!(err, "Duplicate payment hash");
8179         } else { panic!(); }
8180         let mut block = {
8181                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8182                 Block {
8183                         header: BlockHeader {
8184                                 version: 0x2000000,
8185                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8186                                 merkle_root: TxMerkleNode::all_zeros(),
8187                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8188                         txdata: vec![],
8189                 }
8190         };
8191         connect_block(&nodes[1], &block);
8192         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8193                 assert_eq!(err, "Duplicate payment hash");
8194         } else { panic!(); }
8195
8196         // If we then connect the second block, we should be able to register the same payment hash
8197         // again (this time getting a new payment secret).
8198         block.header.prev_blockhash = block.header.block_hash();
8199         block.header.time += 1;
8200         connect_block(&nodes[1], &block);
8201         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8202         assert_ne!(payment_secret_1, our_payment_secret);
8203
8204         {
8205                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8206                 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret), PaymentId(payment_hash.0)).unwrap();
8207                 check_added_monitors!(nodes[0], 1);
8208                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8209                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8210                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8211                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8212         }
8213         // Note that after leaving the above scope we have no knowledge of any arguments or return
8214         // values from previous calls.
8215         expect_pending_htlcs_forwardable!(nodes[1]);
8216         let events = nodes[1].node.get_and_clear_pending_events();
8217         assert_eq!(events.len(), 1);
8218         match events[0] {
8219                 Event::PaymentClaimable { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8220                         assert!(payment_preimage.is_none());
8221                         assert_eq!(payment_secret, our_payment_secret);
8222                         // We don't actually have the payment preimage with which to claim this payment!
8223                 },
8224                 _ => panic!("Unexpected event"),
8225         }
8226 }
8227
8228 #[test]
8229 fn test_bad_secret_hash() {
8230         // Simple test of unregistered payment hash/invalid payment secret handling
8231         let chanmon_cfgs = create_chanmon_cfgs(2);
8232         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8233         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8234         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8235
8236         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8237
8238         let random_payment_hash = PaymentHash([42; 32]);
8239         let random_payment_secret = PaymentSecret([43; 32]);
8240         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8241         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8242
8243         // All the below cases should end up being handled exactly identically, so we macro the
8244         // resulting events.
8245         macro_rules! handle_unknown_invalid_payment_data {
8246                 ($payment_hash: expr) => {
8247                         check_added_monitors!(nodes[0], 1);
8248                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8249                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8250                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8251                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8252
8253                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8254                         // again to process the pending backwards-failure of the HTLC
8255                         expect_pending_htlcs_forwardable!(nodes[1]);
8256                         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8257                         check_added_monitors!(nodes[1], 1);
8258
8259                         // We should fail the payment back
8260                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8261                         match events.pop().unwrap() {
8262                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8263                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8264                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8265                                 },
8266                                 _ => panic!("Unexpected event"),
8267                         }
8268                 }
8269         }
8270
8271         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8272         // Error data is the HTLC value (100,000) and current block height
8273         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8274
8275         // Send a payment with the right payment hash but the wrong payment secret
8276         nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8277         handle_unknown_invalid_payment_data!(our_payment_hash);
8278         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8279
8280         // Send a payment with a random payment hash, but the right payment secret
8281         nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8282         handle_unknown_invalid_payment_data!(random_payment_hash);
8283         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8284
8285         // Send a payment with a random payment hash and random payment secret
8286         nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8287         handle_unknown_invalid_payment_data!(random_payment_hash);
8288         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8289 }
8290
8291 #[test]
8292 fn test_update_err_monitor_lockdown() {
8293         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8294         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8295         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8296         // error.
8297         //
8298         // This scenario may happen in a watchtower setup, where watchtower process a block height
8299         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8300         // commitment at same time.
8301
8302         let chanmon_cfgs = create_chanmon_cfgs(2);
8303         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8304         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8305         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8306
8307         // Create some initial channel
8308         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8309         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8310
8311         // Rebalance the network to generate htlc in the two directions
8312         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8313
8314         // Route a HTLC from node 0 to node 1 (but don't settle)
8315         let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8316
8317         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8318         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8319         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8320         let persister = test_utils::TestPersister::new();
8321         let watchtower = {
8322                 let new_monitor = {
8323                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8324                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8325                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8326                         assert!(new_monitor == *monitor);
8327                         new_monitor
8328                 };
8329                 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);
8330                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8331                 watchtower
8332         };
8333         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8334         let block = Block { header, txdata: vec![] };
8335         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8336         // transaction lock time requirements here.
8337         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8338         watchtower.chain_monitor.block_connected(&block, 200);
8339
8340         // Try to update ChannelMonitor
8341         nodes[1].node.claim_funds(preimage);
8342         check_added_monitors!(nodes[1], 1);
8343         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8344
8345         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8346         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8347         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8348         {
8349                 let mut node_0_per_peer_lock;
8350                 let mut node_0_peer_state_lock;
8351                 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8352                 if let Ok(update) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8353                         assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8354                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8355                 } else { assert!(false); }
8356         }
8357         // Our local monitor is in-sync and hasn't processed yet timeout
8358         check_added_monitors!(nodes[0], 1);
8359         let events = nodes[0].node.get_and_clear_pending_events();
8360         assert_eq!(events.len(), 1);
8361 }
8362
8363 #[test]
8364 fn test_concurrent_monitor_claim() {
8365         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8366         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8367         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8368         // state N+1 confirms. Alice claims output from state N+1.
8369
8370         let chanmon_cfgs = create_chanmon_cfgs(2);
8371         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8372         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8373         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8374
8375         // Create some initial channel
8376         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8377         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8378
8379         // Rebalance the network to generate htlc in the two directions
8380         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8381
8382         // Route a HTLC from node 0 to node 1 (but don't settle)
8383         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8384
8385         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8386         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8387         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8388         let persister = test_utils::TestPersister::new();
8389         let watchtower_alice = {
8390                 let new_monitor = {
8391                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8392                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8393                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8394                         assert!(new_monitor == *monitor);
8395                         new_monitor
8396                 };
8397                 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);
8398                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8399                 watchtower
8400         };
8401         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8402         let block = Block { header, txdata: vec![] };
8403         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8404         // transaction lock time requirements here.
8405         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));
8406         watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8407
8408         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8409         {
8410                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8411                 assert_eq!(txn.len(), 2);
8412                 txn.clear();
8413         }
8414
8415         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8416         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8417         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8418         let persister = test_utils::TestPersister::new();
8419         let watchtower_bob = {
8420                 let new_monitor = {
8421                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8422                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8423                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8424                         assert!(new_monitor == *monitor);
8425                         new_monitor
8426                 };
8427                 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);
8428                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8429                 watchtower
8430         };
8431         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8432         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8433
8434         // Route another payment to generate another update with still previous HTLC pending
8435         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8436         {
8437                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
8438         }
8439         check_added_monitors!(nodes[1], 1);
8440
8441         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8442         assert_eq!(updates.update_add_htlcs.len(), 1);
8443         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8444         {
8445                 let mut node_0_per_peer_lock;
8446                 let mut node_0_peer_state_lock;
8447                 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8448                 if let Ok(update) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8449                         // Watchtower Alice should already have seen the block and reject the update
8450                         assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8451                         assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8452                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8453                 } else { assert!(false); }
8454         }
8455         // Our local monitor is in-sync and hasn't processed yet timeout
8456         check_added_monitors!(nodes[0], 1);
8457
8458         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8459         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8460         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8461
8462         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8463         let bob_state_y;
8464         {
8465                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8466                 assert_eq!(txn.len(), 2);
8467                 bob_state_y = txn[0].clone();
8468                 txn.clear();
8469         };
8470
8471         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8472         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8473         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);
8474         {
8475                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8476                 assert_eq!(htlc_txn.len(), 1);
8477                 check_spends!(htlc_txn[0], bob_state_y);
8478         }
8479 }
8480
8481 #[test]
8482 fn test_pre_lockin_no_chan_closed_update() {
8483         // Test that if a peer closes a channel in response to a funding_created message we don't
8484         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8485         // message).
8486         //
8487         // Doing so would imply a channel monitor update before the initial channel monitor
8488         // registration, violating our API guarantees.
8489         //
8490         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8491         // then opening a second channel with the same funding output as the first (which is not
8492         // rejected because the first channel does not exist in the ChannelManager) and closing it
8493         // before receiving funding_signed.
8494         let chanmon_cfgs = create_chanmon_cfgs(2);
8495         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8496         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8497         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8498
8499         // Create an initial channel
8500         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8501         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8502         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8503         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8504         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8505
8506         // Move the first channel through the funding flow...
8507         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8508
8509         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8510         check_added_monitors!(nodes[0], 0);
8511
8512         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8513         let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8514         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8515         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8516         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true);
8517 }
8518
8519 #[test]
8520 fn test_htlc_no_detection() {
8521         // This test is a mutation to underscore the detection logic bug we had
8522         // before #653. HTLC value routed is above the remaining balance, thus
8523         // inverting HTLC and `to_remote` output. HTLC will come second and
8524         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8525         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8526         // outputs order detection for correct spending children filtring.
8527
8528         let chanmon_cfgs = create_chanmon_cfgs(2);
8529         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8530         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8531         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8532
8533         // Create some initial channels
8534         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8535
8536         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8537         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8538         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8539         assert_eq!(local_txn[0].input.len(), 1);
8540         assert_eq!(local_txn[0].output.len(), 3);
8541         check_spends!(local_txn[0], chan_1.3);
8542
8543         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8544         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8545         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8546         // We deliberately connect the local tx twice as this should provoke a failure calling
8547         // this test before #653 fix.
8548         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);
8549         check_closed_broadcast!(nodes[0], true);
8550         check_added_monitors!(nodes[0], 1);
8551         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8552         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8553
8554         let htlc_timeout = {
8555                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8556                 assert_eq!(node_txn.len(), 1);
8557                 assert_eq!(node_txn[0].input.len(), 1);
8558                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8559                 check_spends!(node_txn[0], local_txn[0]);
8560                 node_txn[0].clone()
8561         };
8562
8563         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8564         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8565         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8566         expect_payment_failed!(nodes[0], our_payment_hash, false);
8567 }
8568
8569 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8570         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8571         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8572         // Carol, Alice would be the upstream node, and Carol the downstream.)
8573         //
8574         // Steps of the test:
8575         // 1) Alice sends a HTLC to Carol through Bob.
8576         // 2) Carol doesn't settle the HTLC.
8577         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8578         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8579         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8580         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8581         // 5) Carol release the preimage to Bob off-chain.
8582         // 6) Bob claims the offered output on the broadcasted commitment.
8583         let chanmon_cfgs = create_chanmon_cfgs(3);
8584         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8585         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8586         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8587
8588         // Create some initial channels
8589         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8590         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8591
8592         // Steps (1) and (2):
8593         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8594         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8595
8596         // Check that Alice's commitment transaction now contains an output for this HTLC.
8597         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8598         check_spends!(alice_txn[0], chan_ab.3);
8599         assert_eq!(alice_txn[0].output.len(), 2);
8600         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8601         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8602         assert_eq!(alice_txn.len(), 2);
8603
8604         // Steps (3) and (4):
8605         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8606         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8607         let mut force_closing_node = 0; // Alice force-closes
8608         let mut counterparty_node = 1; // Bob if Alice force-closes
8609
8610         // Bob force-closes
8611         if !broadcast_alice {
8612                 force_closing_node = 1;
8613                 counterparty_node = 0;
8614         }
8615         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8616         check_closed_broadcast!(nodes[force_closing_node], true);
8617         check_added_monitors!(nodes[force_closing_node], 1);
8618         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8619         if go_onchain_before_fulfill {
8620                 let txn_to_broadcast = match broadcast_alice {
8621                         true => alice_txn.clone(),
8622                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8623                 };
8624                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8625                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8626                 if broadcast_alice {
8627                         check_closed_broadcast!(nodes[1], true);
8628                         check_added_monitors!(nodes[1], 1);
8629                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8630                 }
8631         }
8632
8633         // Step (5):
8634         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8635         // process of removing the HTLC from their commitment transactions.
8636         nodes[2].node.claim_funds(payment_preimage);
8637         check_added_monitors!(nodes[2], 1);
8638         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8639
8640         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8641         assert!(carol_updates.update_add_htlcs.is_empty());
8642         assert!(carol_updates.update_fail_htlcs.is_empty());
8643         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8644         assert!(carol_updates.update_fee.is_none());
8645         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8646
8647         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8648         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8649         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8650         if !go_onchain_before_fulfill && broadcast_alice {
8651                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8652                 assert_eq!(events.len(), 1);
8653                 match events[0] {
8654                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8655                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8656                         },
8657                         _ => panic!("Unexpected event"),
8658                 };
8659         }
8660         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8661         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8662         // Carol<->Bob's updated commitment transaction info.
8663         check_added_monitors!(nodes[1], 2);
8664
8665         let events = nodes[1].node.get_and_clear_pending_msg_events();
8666         assert_eq!(events.len(), 2);
8667         let bob_revocation = match events[0] {
8668                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8669                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8670                         (*msg).clone()
8671                 },
8672                 _ => panic!("Unexpected event"),
8673         };
8674         let bob_updates = match events[1] {
8675                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8676                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8677                         (*updates).clone()
8678                 },
8679                 _ => panic!("Unexpected event"),
8680         };
8681
8682         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8683         check_added_monitors!(nodes[2], 1);
8684         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8685         check_added_monitors!(nodes[2], 1);
8686
8687         let events = nodes[2].node.get_and_clear_pending_msg_events();
8688         assert_eq!(events.len(), 1);
8689         let carol_revocation = match events[0] {
8690                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8691                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8692                         (*msg).clone()
8693                 },
8694                 _ => panic!("Unexpected event"),
8695         };
8696         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8697         check_added_monitors!(nodes[1], 1);
8698
8699         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8700         // here's where we put said channel's commitment tx on-chain.
8701         let mut txn_to_broadcast = alice_txn.clone();
8702         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8703         if !go_onchain_before_fulfill {
8704                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8705                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8706                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8707                 if broadcast_alice {
8708                         check_closed_broadcast!(nodes[1], true);
8709                         check_added_monitors!(nodes[1], 1);
8710                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8711                 }
8712                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8713                 if broadcast_alice {
8714                         assert_eq!(bob_txn.len(), 1);
8715                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8716                 } else {
8717                         assert_eq!(bob_txn.len(), 2);
8718                         check_spends!(bob_txn[0], chan_ab.3);
8719                 }
8720         }
8721
8722         // Step (6):
8723         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8724         // broadcasted commitment transaction.
8725         {
8726                 let script_weight = match broadcast_alice {
8727                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8728                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8729                 };
8730                 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8731                 // Bob force-closed and broadcasts the commitment transaction along with a
8732                 // HTLC-output-claiming transaction.
8733                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8734                 if broadcast_alice {
8735                         assert_eq!(bob_txn.len(), 1);
8736                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8737                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8738                 } else {
8739                         assert_eq!(bob_txn.len(), 2);
8740                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8741                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8742                 }
8743         }
8744 }
8745
8746 #[test]
8747 fn test_onchain_htlc_settlement_after_close() {
8748         do_test_onchain_htlc_settlement_after_close(true, true);
8749         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8750         do_test_onchain_htlc_settlement_after_close(true, false);
8751         do_test_onchain_htlc_settlement_after_close(false, false);
8752 }
8753
8754 #[test]
8755 fn test_duplicate_temporary_channel_id_from_different_peers() {
8756         // Tests that we can accept two different `OpenChannel` requests with the same
8757         // `temporary_channel_id`, as long as they are from different peers.
8758         let chanmon_cfgs = create_chanmon_cfgs(3);
8759         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8760         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8761         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8762
8763         // Create an first channel channel
8764         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8765         let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8766
8767         // Create an second channel
8768         nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8769         let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8770
8771         // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8772         // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8773         open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8774
8775         // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8776         // `temporary_channel_id` as they are from different peers.
8777         nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8778         {
8779                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8780                 assert_eq!(events.len(), 1);
8781                 match &events[0] {
8782                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8783                                 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8784                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8785                         },
8786                         _ => panic!("Unexpected event"),
8787                 }
8788         }
8789
8790         nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8791         {
8792                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8793                 assert_eq!(events.len(), 1);
8794                 match &events[0] {
8795                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8796                                 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8797                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8798                         },
8799                         _ => panic!("Unexpected event"),
8800                 }
8801         }
8802 }
8803
8804 #[test]
8805 fn test_duplicate_chan_id() {
8806         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8807         // already open we reject it and keep the old channel.
8808         //
8809         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8810         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8811         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8812         // updating logic for the existing channel.
8813         let chanmon_cfgs = create_chanmon_cfgs(2);
8814         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8815         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8816         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8817
8818         // Create an initial channel
8819         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8820         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8821         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8822         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()));
8823
8824         // Try to create a second channel with the same temporary_channel_id as the first and check
8825         // that it is rejected.
8826         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8827         {
8828                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8829                 assert_eq!(events.len(), 1);
8830                 match events[0] {
8831                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8832                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8833                                 // first (valid) and second (invalid) channels are closed, given they both have
8834                                 // the same non-temporary channel_id. However, currently we do not, so we just
8835                                 // move forward with it.
8836                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8837                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8838                         },
8839                         _ => panic!("Unexpected event"),
8840                 }
8841         }
8842
8843         // Move the first channel through the funding flow...
8844         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8845
8846         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8847         check_added_monitors!(nodes[0], 0);
8848
8849         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8850         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8851         {
8852                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8853                 assert_eq!(added_monitors.len(), 1);
8854                 assert_eq!(added_monitors[0].0, funding_output);
8855                 added_monitors.clear();
8856         }
8857         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8858
8859         let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8860         let channel_id = funding_outpoint.to_channel_id();
8861
8862         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8863         // temporary one).
8864
8865         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8866         // Technically this is allowed by the spec, but we don't support it and there's little reason
8867         // to. Still, it shouldn't cause any other issues.
8868         open_chan_msg.temporary_channel_id = channel_id;
8869         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8870         {
8871                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8872                 assert_eq!(events.len(), 1);
8873                 match events[0] {
8874                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8875                                 // Technically, at this point, nodes[1] would be justified in thinking both
8876                                 // channels are closed, but currently we do not, so we just move forward with it.
8877                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8878                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8879                         },
8880                         _ => panic!("Unexpected event"),
8881                 }
8882         }
8883
8884         // Now try to create a second channel which has a duplicate funding output.
8885         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8886         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8887         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
8888         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()));
8889         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8890
8891         let funding_created = {
8892                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8893                 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
8894                 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
8895                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8896                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8897                 // channelmanager in a possibly nonsense state instead).
8898                 let mut as_chan = a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8899                 let logger = test_utils::TestLogger::new();
8900                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8901         };
8902         check_added_monitors!(nodes[0], 0);
8903         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8904         // At this point we'll look up if the channel_id is present and immediately fail the channel
8905         // without trying to persist the `ChannelMonitor`.
8906         check_added_monitors!(nodes[1], 0);
8907
8908         // ...still, nodes[1] will reject the duplicate channel.
8909         {
8910                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8911                 assert_eq!(events.len(), 1);
8912                 match events[0] {
8913                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8914                                 // Technically, at this point, nodes[1] would be justified in thinking both
8915                                 // channels are closed, but currently we do not, so we just move forward with it.
8916                                 assert_eq!(msg.channel_id, channel_id);
8917                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8918                         },
8919                         _ => panic!("Unexpected event"),
8920                 }
8921         }
8922
8923         // finally, finish creating the original channel and send a payment over it to make sure
8924         // everything is functional.
8925         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8926         {
8927                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8928                 assert_eq!(added_monitors.len(), 1);
8929                 assert_eq!(added_monitors[0].0, funding_output);
8930                 added_monitors.clear();
8931         }
8932
8933         let events_4 = nodes[0].node.get_and_clear_pending_events();
8934         assert_eq!(events_4.len(), 0);
8935         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8936         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8937
8938         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8939         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
8940         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8941
8942         send_payment(&nodes[0], &[&nodes[1]], 8000000);
8943 }
8944
8945 #[test]
8946 fn test_error_chans_closed() {
8947         // Test that we properly handle error messages, closing appropriate channels.
8948         //
8949         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8950         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8951         // we can test various edge cases around it to ensure we don't regress.
8952         let chanmon_cfgs = create_chanmon_cfgs(3);
8953         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8954         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8955         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8956
8957         // Create some initial channels
8958         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8959         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8960         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
8961
8962         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8963         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8964         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8965
8966         // Closing a channel from a different peer has no effect
8967         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8968         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8969
8970         // Closing one channel doesn't impact others
8971         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8972         check_added_monitors!(nodes[0], 1);
8973         check_closed_broadcast!(nodes[0], false);
8974         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
8975         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8976         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8977         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);
8978         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);
8979
8980         // A null channel ID should close all channels
8981         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8982         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8983         check_added_monitors!(nodes[0], 2);
8984         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
8985         let events = nodes[0].node.get_and_clear_pending_msg_events();
8986         assert_eq!(events.len(), 2);
8987         match events[0] {
8988                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8989                         assert_eq!(msg.contents.flags & 2, 2);
8990                 },
8991                 _ => panic!("Unexpected event"),
8992         }
8993         match events[1] {
8994                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8995                         assert_eq!(msg.contents.flags & 2, 2);
8996                 },
8997                 _ => panic!("Unexpected event"),
8998         }
8999         // Note that at this point users of a standard PeerHandler will end up calling
9000         // peer_disconnected.
9001         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9002         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9003
9004         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
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
9009 #[test]
9010 fn test_invalid_funding_tx() {
9011         // Test that we properly handle invalid funding transactions sent to us from a peer.
9012         //
9013         // Previously, all other major lightning implementations had failed to properly sanitize
9014         // funding transactions from their counterparties, leading to a multi-implementation critical
9015         // security vulnerability (though we always sanitized properly, we've previously had
9016         // un-released crashes in the sanitization process).
9017         //
9018         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9019         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9020         // gave up on it. We test this here by generating such a transaction.
9021         let chanmon_cfgs = create_chanmon_cfgs(2);
9022         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9023         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9024         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9025
9026         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9027         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()));
9028         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()));
9029
9030         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9031
9032         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9033         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9034         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9035         // its length.
9036         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9037         let wit_program_script: Script = wit_program.into();
9038         for output in tx.output.iter_mut() {
9039                 // Make the confirmed funding transaction have a bogus script_pubkey
9040                 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9041         }
9042
9043         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9044         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()));
9045         check_added_monitors!(nodes[1], 1);
9046
9047         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()));
9048         check_added_monitors!(nodes[0], 1);
9049
9050         let events_1 = nodes[0].node.get_and_clear_pending_events();
9051         assert_eq!(events_1.len(), 0);
9052
9053         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9054         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9055         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9056
9057         let expected_err = "funding tx had wrong script/value or output index";
9058         confirm_transaction_at(&nodes[1], &tx, 1);
9059         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9060         check_added_monitors!(nodes[1], 1);
9061         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9062         assert_eq!(events_2.len(), 1);
9063         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9064                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9065                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9066                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9067                 } else { panic!(); }
9068         } else { panic!(); }
9069         assert_eq!(nodes[1].node.list_channels().len(), 0);
9070
9071         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9072         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9073         // as its not 32 bytes long.
9074         let mut spend_tx = Transaction {
9075                 version: 2i32, lock_time: PackedLockTime::ZERO,
9076                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9077                         previous_output: BitcoinOutPoint {
9078                                 txid: tx.txid(),
9079                                 vout: idx as u32,
9080                         },
9081                         script_sig: Script::new(),
9082                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9083                         witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9084                 }).collect(),
9085                 output: vec![TxOut {
9086                         value: 1000,
9087                         script_pubkey: Script::new(),
9088                 }]
9089         };
9090         check_spends!(spend_tx, tx);
9091         mine_transaction(&nodes[1], &spend_tx);
9092 }
9093
9094 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9095         // In the first version of the chain::Confirm interface, after a refactor was made to not
9096         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9097         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9098         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9099         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9100         // spending transaction until height N+1 (or greater). This was due to the way
9101         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9102         // spending transaction at the height the input transaction was confirmed at, not whether we
9103         // should broadcast a spending transaction at the current height.
9104         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9105         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9106         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9107         // until we learned about an additional block.
9108         //
9109         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9110         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9111         let chanmon_cfgs = create_chanmon_cfgs(3);
9112         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9113         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9114         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9115         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9116
9117         create_announced_chan_between_nodes(&nodes, 0, 1);
9118         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9119         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9120         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9121         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9122
9123         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9124         check_closed_broadcast!(nodes[1], true);
9125         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9126         check_added_monitors!(nodes[1], 1);
9127         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9128         assert_eq!(node_txn.len(), 1);
9129
9130         let conf_height = nodes[1].best_block_info().1;
9131         if !test_height_before_timelock {
9132                 connect_blocks(&nodes[1], 24 * 6);
9133         }
9134         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9135                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9136         if test_height_before_timelock {
9137                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9138                 // generate any events or broadcast any transactions
9139                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9140                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9141         } else {
9142                 // We should broadcast an HTLC transaction spending our funding transaction first
9143                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9144                 assert_eq!(spending_txn.len(), 2);
9145                 assert_eq!(spending_txn[0], node_txn[0]);
9146                 check_spends!(spending_txn[1], node_txn[0]);
9147                 // We should also generate a SpendableOutputs event with the to_self output (as its
9148                 // timelock is up).
9149                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9150                 assert_eq!(descriptor_spend_txn.len(), 1);
9151
9152                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9153                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9154                 // additional block built on top of the current chain.
9155                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9156                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9157                 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 }]);
9158                 check_added_monitors!(nodes[1], 1);
9159
9160                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9161                 assert!(updates.update_add_htlcs.is_empty());
9162                 assert!(updates.update_fulfill_htlcs.is_empty());
9163                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9164                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9165                 assert!(updates.update_fee.is_none());
9166                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9167                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9168                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9169         }
9170 }
9171
9172 #[test]
9173 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9174         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9175         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9176 }
9177
9178 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9179         let chanmon_cfgs = create_chanmon_cfgs(2);
9180         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9181         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9182         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9183
9184         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9185
9186         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9187                 .with_features(nodes[1].node.invoice_features());
9188         let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9189
9190         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9191
9192         {
9193                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9194                 check_added_monitors!(nodes[0], 1);
9195                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9196                 assert_eq!(events.len(), 1);
9197                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9198                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9199                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9200         }
9201         expect_pending_htlcs_forwardable!(nodes[1]);
9202         expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9203
9204         {
9205                 // Note that we use a different PaymentId here to allow us to duplicativly pay
9206                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9207                 check_added_monitors!(nodes[0], 1);
9208                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9209                 assert_eq!(events.len(), 1);
9210                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9211                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9212                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9213                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9214                 // assume the second is a privacy attack (no longer particularly relevant
9215                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9216                 // the first HTLC delivered above.
9217         }
9218
9219         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9220         nodes[1].node.process_pending_htlc_forwards();
9221
9222         if test_for_second_fail_panic {
9223                 // Now we go fail back the first HTLC from the user end.
9224                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9225
9226                 let expected_destinations = vec![
9227                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9228                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9229                 ];
9230                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],  expected_destinations);
9231                 nodes[1].node.process_pending_htlc_forwards();
9232
9233                 check_added_monitors!(nodes[1], 1);
9234                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9235                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9236
9237                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9238                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9239                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9240
9241                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9242                 assert_eq!(failure_events.len(), 4);
9243                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9244                 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9245                 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9246                 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9247         } else {
9248                 // Let the second HTLC fail and claim the first
9249                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9250                 nodes[1].node.process_pending_htlc_forwards();
9251
9252                 check_added_monitors!(nodes[1], 1);
9253                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9254                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9255                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9256
9257                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9258
9259                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9260         }
9261 }
9262
9263 #[test]
9264 fn test_dup_htlc_second_fail_panic() {
9265         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9266         // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9267         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9268         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9269         do_test_dup_htlc_second_rejected(true);
9270 }
9271
9272 #[test]
9273 fn test_dup_htlc_second_rejected() {
9274         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9275         // simply reject the second HTLC but are still able to claim the first HTLC.
9276         do_test_dup_htlc_second_rejected(false);
9277 }
9278
9279 #[test]
9280 fn test_inconsistent_mpp_params() {
9281         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9282         // such HTLC and allow the second to stay.
9283         let chanmon_cfgs = create_chanmon_cfgs(4);
9284         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9285         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9286         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9287
9288         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9289         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9290         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9291         let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9292
9293         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9294                 .with_features(nodes[3].node.invoice_features());
9295         let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9296         assert_eq!(route.paths.len(), 2);
9297         route.paths.sort_by(|path_a, _| {
9298                 // Sort the path so that the path through nodes[1] comes first
9299                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9300                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9301         });
9302
9303         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9304
9305         let cur_height = nodes[0].best_block_info().1;
9306         let payment_id = PaymentId([42; 32]);
9307
9308         let session_privs = {
9309                 // We create a fake route here so that we start with three pending HTLCs, which we'll
9310                 // ultimately have, just not right away.
9311                 let mut dup_route = route.clone();
9312                 dup_route.paths.push(route.paths[1].clone());
9313                 nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(our_payment_secret), payment_id, &dup_route).unwrap()
9314         };
9315         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();
9316         check_added_monitors!(nodes[0], 1);
9317
9318         {
9319                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9320                 assert_eq!(events.len(), 1);
9321                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9322         }
9323         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9324
9325         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();
9326         check_added_monitors!(nodes[0], 1);
9327
9328         {
9329                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9330                 assert_eq!(events.len(), 1);
9331                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9332
9333                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9334                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9335
9336                 expect_pending_htlcs_forwardable!(nodes[2]);
9337                 check_added_monitors!(nodes[2], 1);
9338
9339                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9340                 assert_eq!(events.len(), 1);
9341                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9342
9343                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9344                 check_added_monitors!(nodes[3], 0);
9345                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9346
9347                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9348                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9349                 // post-payment_secrets) and fail back the new HTLC.
9350         }
9351         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9352         nodes[3].node.process_pending_htlc_forwards();
9353         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9354         nodes[3].node.process_pending_htlc_forwards();
9355
9356         check_added_monitors!(nodes[3], 1);
9357
9358         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9359         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9360         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9361
9362         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 }]);
9363         check_added_monitors!(nodes[2], 1);
9364
9365         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9366         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9367         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9368
9369         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9370
9371         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();
9372         check_added_monitors!(nodes[0], 1);
9373
9374         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9375         assert_eq!(events.len(), 1);
9376         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9377
9378         do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9379         let events = nodes[0].node.get_and_clear_pending_events();
9380         assert_eq!(events.len(), 3);
9381         match events[0] {
9382                 Event::PaymentSent { payment_hash, .. } => { // The payment was abandoned earlier, so the fee paid will be None
9383                         assert_eq!(payment_hash, our_payment_hash);
9384                 },
9385                 _ => panic!("Unexpected event")
9386         }
9387         match events[1] {
9388                 Event::PaymentPathSuccessful { payment_hash, .. } => {
9389                         assert_eq!(payment_hash.unwrap(), our_payment_hash);
9390                 },
9391                 _ => panic!("Unexpected event")
9392         }
9393         match events[2] {
9394                 Event::PaymentPathSuccessful { payment_hash, .. } => {
9395                         assert_eq!(payment_hash.unwrap(), our_payment_hash);
9396                 },
9397                 _ => panic!("Unexpected event")
9398         }
9399 }
9400
9401 #[test]
9402 fn test_keysend_payments_to_public_node() {
9403         let chanmon_cfgs = create_chanmon_cfgs(2);
9404         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9405         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9406         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9407
9408         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9409         let network_graph = nodes[0].network_graph.clone();
9410         let payer_pubkey = nodes[0].node.get_our_node_id();
9411         let payee_pubkey = nodes[1].node.get_our_node_id();
9412         let route_params = RouteParameters {
9413                 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9414                 final_value_msat: 10000,
9415         };
9416         let scorer = test_utils::TestScorer::new();
9417         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9418         let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9419
9420         let test_preimage = PaymentPreimage([42; 32]);
9421         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage), PaymentId(test_preimage.0)).unwrap();
9422         check_added_monitors!(nodes[0], 1);
9423         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9424         assert_eq!(events.len(), 1);
9425         let event = events.pop().unwrap();
9426         let path = vec![&nodes[1]];
9427         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9428         claim_payment(&nodes[0], &path, test_preimage);
9429 }
9430
9431 #[test]
9432 fn test_keysend_payments_to_private_node() {
9433         let chanmon_cfgs = create_chanmon_cfgs(2);
9434         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9435         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9436         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9437
9438         let payer_pubkey = nodes[0].node.get_our_node_id();
9439         let payee_pubkey = nodes[1].node.get_our_node_id();
9440
9441         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
9442         let route_params = RouteParameters {
9443                 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9444                 final_value_msat: 10000,
9445         };
9446         let network_graph = nodes[0].network_graph.clone();
9447         let first_hops = nodes[0].node.list_usable_channels();
9448         let scorer = test_utils::TestScorer::new();
9449         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9450         let route = find_route(
9451                 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9452                 nodes[0].logger, &scorer, &random_seed_bytes
9453         ).unwrap();
9454
9455         let test_preimage = PaymentPreimage([42; 32]);
9456         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage), PaymentId(test_preimage.0)).unwrap();
9457         check_added_monitors!(nodes[0], 1);
9458         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9459         assert_eq!(events.len(), 1);
9460         let event = events.pop().unwrap();
9461         let path = vec![&nodes[1]];
9462         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9463         claim_payment(&nodes[0], &path, test_preimage);
9464 }
9465
9466 #[test]
9467 fn test_double_partial_claim() {
9468         // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9469         // time out, the sender resends only some of the MPP parts, then the user processes the
9470         // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9471         // amount.
9472         let chanmon_cfgs = create_chanmon_cfgs(4);
9473         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9474         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9475         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9476
9477         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9478         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9479         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9480         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9481
9482         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9483         assert_eq!(route.paths.len(), 2);
9484         route.paths.sort_by(|path_a, _| {
9485                 // Sort the path so that the path through nodes[1] comes first
9486                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9487                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9488         });
9489
9490         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9491         // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9492         // amount of time to respond to.
9493
9494         // Connect some blocks to time out the payment
9495         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9496         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9497
9498         let failed_destinations = vec![
9499                 HTLCDestination::FailedPayment { payment_hash },
9500                 HTLCDestination::FailedPayment { payment_hash },
9501         ];
9502         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9503
9504         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
9505
9506         // nodes[1] now retries one of the two paths...
9507         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9508         check_added_monitors!(nodes[0], 2);
9509
9510         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9511         assert_eq!(events.len(), 2);
9512         let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9513         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9514
9515         // At this point nodes[3] has received one half of the payment, and the user goes to handle
9516         // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9517         nodes[3].node.claim_funds(payment_preimage);
9518         check_added_monitors!(nodes[3], 0);
9519         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9520 }
9521
9522 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9523 #[derive(Clone, Copy, PartialEq)]
9524 enum ExposureEvent {
9525         /// Breach occurs at HTLC forwarding (see `send_htlc`)
9526         AtHTLCForward,
9527         /// Breach occurs at HTLC reception (see `update_add_htlc`)
9528         AtHTLCReception,
9529         /// Breach occurs at outbound update_fee (see `send_update_fee`)
9530         AtUpdateFeeOutbound,
9531 }
9532
9533 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9534         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9535         // policy.
9536         //
9537         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9538         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9539         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9540         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9541         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9542         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9543         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9544         // might be available again for HTLC processing once the dust bandwidth has cleared up.
9545
9546         let chanmon_cfgs = create_chanmon_cfgs(2);
9547         let mut config = test_default_channel_config();
9548         config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9549         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9550         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9551         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9552
9553         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9554         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9555         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9556         open_channel.max_accepted_htlcs = 60;
9557         if on_holder_tx {
9558                 open_channel.dust_limit_satoshis = 546;
9559         }
9560         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9561         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9562         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9563
9564         let opt_anchors = false;
9565
9566         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9567
9568         if on_holder_tx {
9569                 let mut node_0_per_peer_lock;
9570                 let mut node_0_peer_state_lock;
9571                 let mut chan = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id);
9572                 chan.holder_dust_limit_satoshis = 546;
9573         }
9574
9575         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9576         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()));
9577         check_added_monitors!(nodes[1], 1);
9578
9579         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()));
9580         check_added_monitors!(nodes[0], 1);
9581
9582         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9583         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9584         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9585
9586         let dust_buffer_feerate = {
9587                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9588                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9589                 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9590                 chan.get_dust_buffer_feerate(None) as u64
9591         };
9592         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;
9593         let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9594
9595         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;
9596         let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9597
9598         let dust_htlc_on_counterparty_tx: u64 = 25;
9599         let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9600
9601         if on_holder_tx {
9602                 if dust_outbound_balance {
9603                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9604                         // Outbound dust balance: 4372 sats
9605                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9606                         for i in 0..dust_outbound_htlc_on_holder_tx {
9607                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9608                                 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); }
9609                         }
9610                 } else {
9611                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9612                         // Inbound dust balance: 4372 sats
9613                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9614                         for _ in 0..dust_inbound_htlc_on_holder_tx {
9615                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9616                         }
9617                 }
9618         } else {
9619                 if dust_outbound_balance {
9620                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9621                         // Outbound dust balance: 5000 sats
9622                         for i in 0..dust_htlc_on_counterparty_tx {
9623                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9624                                 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); }
9625                         }
9626                 } else {
9627                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9628                         // Inbound dust balance: 5000 sats
9629                         for _ in 0..dust_htlc_on_counterparty_tx {
9630                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9631                         }
9632                 }
9633         }
9634
9635         let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9636         if exposure_breach_event == ExposureEvent::AtHTLCForward {
9637                 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 });
9638                 let mut config = UserConfig::default();
9639                 // With default dust exposure: 5000 sats
9640                 if on_holder_tx {
9641                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9642                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9643                         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)));
9644                 } else {
9645                         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)));
9646                 }
9647         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9648                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], if on_holder_tx { dust_inbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat });
9649                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9650                 check_added_monitors!(nodes[1], 1);
9651                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9652                 assert_eq!(events.len(), 1);
9653                 let payment_event = SendEvent::from_event(events.remove(0));
9654                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9655                 // With default dust exposure: 5000 sats
9656                 if on_holder_tx {
9657                         // Outbound dust balance: 6399 sats
9658                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9659                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9660                         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);
9661                 } else {
9662                         // Outbound dust balance: 5200 sats
9663                         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);
9664                 }
9665         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9666                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
9667                 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", ); }
9668                 {
9669                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9670                         *feerate_lock = *feerate_lock * 10;
9671                 }
9672                 nodes[0].node.timer_tick_occurred();
9673                 check_added_monitors!(nodes[0], 1);
9674                 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9675         }
9676
9677         let _ = nodes[0].node.get_and_clear_pending_msg_events();
9678         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9679         added_monitors.clear();
9680 }
9681
9682 #[test]
9683 fn test_max_dust_htlc_exposure() {
9684         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9685         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9686         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9687         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9688         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9689         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9690         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9691         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9692         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9693         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9694         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9695         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
9696 }
9697
9698 #[test]
9699 fn test_non_final_funding_tx() {
9700         let chanmon_cfgs = create_chanmon_cfgs(2);
9701         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9702         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9703         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9704
9705         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9706         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9707         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9708         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9709         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9710
9711         let best_height = nodes[0].node.best_block.read().unwrap().height();
9712
9713         let chan_id = *nodes[0].network_chan_count.borrow();
9714         let events = nodes[0].node.get_and_clear_pending_events();
9715         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9716         assert_eq!(events.len(), 1);
9717         let mut tx = match events[0] {
9718                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9719                         // Timelock the transaction _beyond_ the best client height + 2.
9720                         Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 3), input: vec![input], output: vec![TxOut {
9721                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9722                         }]}
9723                 },
9724                 _ => panic!("Unexpected event"),
9725         };
9726         // Transaction should fail as it's evaluated as non-final for propagation.
9727         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9728                 Err(APIError::APIMisuseError { err }) => {
9729                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9730                 },
9731                 _ => panic!()
9732         }
9733
9734         // However, transaction should be accepted if it's in a +2 headroom from best block.
9735         tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9736         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9737         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9738 }
9739
9740 #[test]
9741 fn accept_busted_but_better_fee() {
9742         // If a peer sends us a fee update that is too low, but higher than our previous channel
9743         // feerate, we should accept it. In the future we may want to consider closing the channel
9744         // later, but for now we only accept the update.
9745         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9746         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9747         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9748         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9749
9750         create_chan_between_nodes(&nodes[0], &nodes[1]);
9751
9752         // Set nodes[1] to expect 5,000 sat/kW.
9753         {
9754                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9755                 *feerate_lock = 5000;
9756         }
9757
9758         // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9759         {
9760                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9761                 *feerate_lock = 1000;
9762         }
9763         nodes[0].node.timer_tick_occurred();
9764         check_added_monitors!(nodes[0], 1);
9765
9766         let events = nodes[0].node.get_and_clear_pending_msg_events();
9767         assert_eq!(events.len(), 1);
9768         match events[0] {
9769                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9770                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9771                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9772                 },
9773                 _ => panic!("Unexpected event"),
9774         };
9775
9776         // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9777         // it.
9778         {
9779                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9780                 *feerate_lock = 2000;
9781         }
9782         nodes[0].node.timer_tick_occurred();
9783         check_added_monitors!(nodes[0], 1);
9784
9785         let events = nodes[0].node.get_and_clear_pending_msg_events();
9786         assert_eq!(events.len(), 1);
9787         match events[0] {
9788                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9789                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9790                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9791                 },
9792                 _ => panic!("Unexpected event"),
9793         };
9794
9795         // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9796         // channel.
9797         {
9798                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9799                 *feerate_lock = 1000;
9800         }
9801         nodes[0].node.timer_tick_occurred();
9802         check_added_monitors!(nodes[0], 1);
9803
9804         let events = nodes[0].node.get_and_clear_pending_msg_events();
9805         assert_eq!(events.len(), 1);
9806         match events[0] {
9807                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9808                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9809                         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9810                                 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() });
9811                         check_closed_broadcast!(nodes[1], true);
9812                         check_added_monitors!(nodes[1], 1);
9813                 },
9814                 _ => panic!("Unexpected event"),
9815         };
9816 }
9817
9818 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9819         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9820         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9821         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9822         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9823         let min_final_cltv_expiry_delta = 120;
9824         let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9825                 min_final_cltv_expiry_delta - 2 };
9826         let recv_value = 100_000;
9827
9828         create_chan_between_nodes(&nodes[0], &nodes[1]);
9829
9830         let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
9831         let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
9832                 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
9833                         Some(recv_value), Some(min_final_cltv_expiry_delta));
9834                 (payment_hash, payment_preimage, payment_secret)
9835         } else {
9836                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
9837                 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
9838         };
9839         let route = get_route!(nodes[0], payment_parameters, recv_value, final_cltv_expiry_delta as u32).unwrap();
9840         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9841         check_added_monitors!(nodes[0], 1);
9842         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9843         assert_eq!(events.len(), 1);
9844         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9845         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9846         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9847         expect_pending_htlcs_forwardable!(nodes[1]);
9848
9849         if valid_delta {
9850                 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
9851                         None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
9852
9853                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9854         } else {
9855                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9856
9857                 check_added_monitors!(nodes[1], 1);
9858
9859                 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9860                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
9861                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
9862
9863                 expect_payment_failed!(nodes[0], payment_hash, true);
9864         }
9865 }
9866
9867 #[test]
9868 fn test_payment_with_custom_min_cltv_expiry_delta() {
9869         do_payment_with_custom_min_final_cltv_expiry(false, false);
9870         do_payment_with_custom_min_final_cltv_expiry(false, true);
9871         do_payment_with_custom_min_final_cltv_expiry(true, false);
9872         do_payment_with_custom_min_final_cltv_expiry(true, true);
9873 }