Merge pull request #2006 from TheBlueMatt/2023-02-no-recursive-read-locks
[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::ln::{PaymentPreimage, PaymentSecret, PaymentHash};
22 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};
23 use crate::ln::channelmanager::{self, PaymentId, RAACommitmentOrder, PaymentSendFailure, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA};
24 use crate::ln::channel::{Channel, ChannelError};
25 use crate::ln::{chan_utils, onion_utils};
26 use crate::ln::chan_utils::{OFFERED_HTLC_SCRIPT_WEIGHT, htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
27 use crate::routing::gossip::{NetworkGraph, NetworkUpdate};
28 use crate::routing::router::{PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
29 use crate::ln::features::{ChannelFeatures, NodeFeatures};
30 use crate::ln::msgs;
31 use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
32 use crate::util::enforcing_trait_impls::EnforcingSigner;
33 use crate::util::test_utils;
34 use crate::util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose, ClosureReason, HTLCDestination};
35 use crate::util::errors::APIError;
36 use crate::util::ser::{Writeable, ReadableArgs};
37 use crate::util::config::UserConfig;
38
39 use bitcoin::hash_types::BlockHash;
40 use bitcoin::blockdata::block::{Block, BlockHeader};
41 use bitcoin::blockdata::script::{Builder, Script};
42 use bitcoin::blockdata::opcodes;
43 use bitcoin::blockdata::constants::genesis_block;
44 use bitcoin::network::constants::Network;
45 use bitcoin::{PackedLockTime, Sequence, Transaction, TxIn, TxMerkleNode, TxOut, Witness};
46 use bitcoin::OutPoint as BitcoinOutPoint;
47
48 use bitcoin::secp256k1::Secp256k1;
49 use bitcoin::secp256k1::{PublicKey,SecretKey};
50
51 use regex;
52
53 use crate::io;
54 use crate::prelude::*;
55 use alloc::collections::BTreeSet;
56 use core::default::Default;
57 use core::iter::repeat;
58 use bitcoin::hashes::Hash;
59 use crate::sync::{Arc, Mutex};
60
61 use crate::ln::functional_test_utils::*;
62 use crate::ln::chan_utils::CommitmentTransaction;
63
64 #[test]
65 fn test_insane_channel_opens() {
66         // Stand up a network of 2 nodes
67         use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
68         let mut cfg = UserConfig::default();
69         cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
70         let chanmon_cfgs = create_chanmon_cfgs(2);
71         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
72         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
73         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
74
75         // Instantiate channel parameters where we push the maximum msats given our
76         // funding satoshis
77         let channel_value_sat = 31337; // same as funding satoshis
78         let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
79         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
80
81         // Have node0 initiate a channel to node1 with aforementioned parameters
82         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
83
84         // Extract the channel open message from node0 to node1
85         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
86
87         // Test helper that asserts we get the correct error string given a mutator
88         // that supposedly makes the channel open message insane
89         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
90                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &message_mutator(open_channel_message.clone()));
91                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
92                 assert_eq!(msg_events.len(), 1);
93                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
94                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
95                         match action {
96                                 &ErrorAction::SendErrorMessage { .. } => {
97                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
98                                 },
99                                 _ => panic!("unexpected event!"),
100                         }
101                 } else { assert!(false); }
102         };
103
104         use crate::ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
105
106         // Test all mutations that would make the channel open message insane
107         insane_open_helper(format!("Per our config, funding must be at most {}. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1, TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2; msg });
108         insane_open_helper(format!("Funding must be smaller than the total bitcoin supply. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS; msg });
109
110         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
111
112         insane_open_helper(r"push_msat \d+ was larger than channel amount minus reserve \(\d+\)", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
113
114         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
115
116         insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
117
118         insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
119
120         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
121
122         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
123 }
124
125 #[test]
126 fn test_funding_exceeds_no_wumbo_limit() {
127         // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
128         // them.
129         use crate::ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
130         let chanmon_cfgs = create_chanmon_cfgs(2);
131         let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
132         *node_cfgs[1].override_init_features.borrow_mut() = Some(channelmanager::provided_init_features(&test_default_channel_config()).clear_wumbo());
133         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
134         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
135
136         match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
137                 Err(APIError::APIMisuseError { err }) => {
138                         assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
139                 },
140                 _ => panic!()
141         }
142 }
143
144 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
145         // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
146         // but only for them. Because some LSPs do it with some level of trust of the clients (for a
147         // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
148         // in normal testing, we test it explicitly here.
149         let chanmon_cfgs = create_chanmon_cfgs(2);
150         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
151         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
152         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
153         let default_config = UserConfig::default();
154
155         // Have node0 initiate a channel to node1 with aforementioned parameters
156         let mut push_amt = 100_000_000;
157         let feerate_per_kw = 253;
158         let opt_anchors = false;
159         push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
160         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
161
162         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, if send_from_initiator { 0 } else { push_amt }, 42, None).unwrap();
163         let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
164         if !send_from_initiator {
165                 open_channel_message.channel_reserve_satoshis = 0;
166                 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
167         }
168         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
169
170         // Extract the channel accept message from node1 to node0
171         let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
172         if send_from_initiator {
173                 accept_channel_message.channel_reserve_satoshis = 0;
174                 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
175         }
176         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
177         {
178                 let sender_node = if send_from_initiator { &nodes[1] } else { &nodes[0] };
179                 let counterparty_node = if send_from_initiator { &nodes[0] } else { &nodes[1] };
180                 let mut sender_node_per_peer_lock;
181                 let mut sender_node_peer_state_lock;
182                 let mut chan = get_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
183                 chan.holder_selected_channel_reserve_satoshis = 0;
184                 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
185         }
186
187         let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
188         let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
189         create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
190
191         // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
192         // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
193         if send_from_initiator {
194                 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
195                         // Note that for outbound channels we have to consider the commitment tx fee and the
196                         // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
197                         // well as an additional HTLC.
198                         - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
199         } else {
200                 send_payment(&nodes[1], &[&nodes[0]], push_amt);
201         }
202 }
203
204 #[test]
205 fn test_counterparty_no_reserve() {
206         do_test_counterparty_no_reserve(true);
207         do_test_counterparty_no_reserve(false);
208 }
209
210 #[test]
211 fn test_async_inbound_update_fee() {
212         let chanmon_cfgs = create_chanmon_cfgs(2);
213         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
214         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
215         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
216         create_announced_chan_between_nodes(&nodes, 0, 1);
217
218         // balancing
219         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
220
221         // A                                        B
222         // update_fee                            ->
223         // send (1) commitment_signed            -.
224         //                                       <- update_add_htlc/commitment_signed
225         // send (2) RAA (awaiting remote revoke) -.
226         // (1) commitment_signed is delivered    ->
227         //                                       .- send (3) RAA (awaiting remote revoke)
228         // (2) RAA is delivered                  ->
229         //                                       .- send (4) commitment_signed
230         //                                       <- (3) RAA is delivered
231         // send (5) commitment_signed            -.
232         //                                       <- (4) commitment_signed is delivered
233         // send (6) RAA                          -.
234         // (5) commitment_signed is delivered    ->
235         //                                       <- RAA
236         // (6) RAA is delivered                  ->
237
238         // First nodes[0] generates an update_fee
239         {
240                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
241                 *feerate_lock += 20;
242         }
243         nodes[0].node.timer_tick_occurred();
244         check_added_monitors!(nodes[0], 1);
245
246         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
247         assert_eq!(events_0.len(), 1);
248         let (update_msg, commitment_signed) = match events_0[0] { // (1)
249                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
250                         (update_fee.as_ref(), commitment_signed)
251                 },
252                 _ => panic!("Unexpected event"),
253         };
254
255         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
256
257         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
258         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
259         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
260         check_added_monitors!(nodes[1], 1);
261
262         let payment_event = {
263                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
264                 assert_eq!(events_1.len(), 1);
265                 SendEvent::from_event(events_1.remove(0))
266         };
267         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
268         assert_eq!(payment_event.msgs.len(), 1);
269
270         // ...now when the messages get delivered everyone should be happy
271         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
272         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
273         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
274         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
275         check_added_monitors!(nodes[0], 1);
276
277         // deliver(1), generate (3):
278         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
279         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
280         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
281         check_added_monitors!(nodes[1], 1);
282
283         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
284         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
285         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
286         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
287         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
288         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
289         assert!(bs_update.update_fee.is_none()); // (4)
290         check_added_monitors!(nodes[1], 1);
291
292         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
293         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
294         assert!(as_update.update_add_htlcs.is_empty()); // (5)
295         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
296         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
297         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
298         assert!(as_update.update_fee.is_none()); // (5)
299         check_added_monitors!(nodes[0], 1);
300
301         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
302         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
303         // only (6) so get_event_msg's assert(len == 1) passes
304         check_added_monitors!(nodes[0], 1);
305
306         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
307         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
308         check_added_monitors!(nodes[1], 1);
309
310         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
311         check_added_monitors!(nodes[0], 1);
312
313         let events_2 = nodes[0].node.get_and_clear_pending_events();
314         assert_eq!(events_2.len(), 1);
315         match events_2[0] {
316                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
317                 _ => panic!("Unexpected event"),
318         }
319
320         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
321         check_added_monitors!(nodes[1], 1);
322 }
323
324 #[test]
325 fn test_update_fee_unordered_raa() {
326         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
327         // crash in an earlier version of the update_fee patch)
328         let chanmon_cfgs = create_chanmon_cfgs(2);
329         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
330         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
331         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
332         create_announced_chan_between_nodes(&nodes, 0, 1);
333
334         // balancing
335         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
336
337         // First nodes[0] generates an update_fee
338         {
339                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
340                 *feerate_lock += 20;
341         }
342         nodes[0].node.timer_tick_occurred();
343         check_added_monitors!(nodes[0], 1);
344
345         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
346         assert_eq!(events_0.len(), 1);
347         let update_msg = match events_0[0] { // (1)
348                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
349                         update_fee.as_ref()
350                 },
351                 _ => panic!("Unexpected event"),
352         };
353
354         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
355
356         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
357         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
358         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
359         check_added_monitors!(nodes[1], 1);
360
361         let payment_event = {
362                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
363                 assert_eq!(events_1.len(), 1);
364                 SendEvent::from_event(events_1.remove(0))
365         };
366         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
367         assert_eq!(payment_event.msgs.len(), 1);
368
369         // ...now when the messages get delivered everyone should be happy
370         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
371         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
372         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
373         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
374         check_added_monitors!(nodes[0], 1);
375
376         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
377         check_added_monitors!(nodes[1], 1);
378
379         // We can't continue, sadly, because our (1) now has a bogus signature
380 }
381
382 #[test]
383 fn test_multi_flight_update_fee() {
384         let chanmon_cfgs = create_chanmon_cfgs(2);
385         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
386         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
387         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
388         create_announced_chan_between_nodes(&nodes, 0, 1);
389
390         // A                                        B
391         // update_fee/commitment_signed          ->
392         //                                       .- send (1) RAA and (2) commitment_signed
393         // update_fee (never committed)          ->
394         // (3) update_fee                        ->
395         // We have to manually generate the above update_fee, it is allowed by the protocol but we
396         // don't track which updates correspond to which revoke_and_ack responses so we're in
397         // AwaitingRAA mode and will not generate the update_fee yet.
398         //                                       <- (1) RAA delivered
399         // (3) is generated and send (4) CS      -.
400         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
401         // know the per_commitment_point to use for it.
402         //                                       <- (2) commitment_signed delivered
403         // revoke_and_ack                        ->
404         //                                          B should send no response here
405         // (4) commitment_signed delivered       ->
406         //                                       <- RAA/commitment_signed delivered
407         // revoke_and_ack                        ->
408
409         // First nodes[0] generates an update_fee
410         let initial_feerate;
411         {
412                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
413                 initial_feerate = *feerate_lock;
414                 *feerate_lock = initial_feerate + 20;
415         }
416         nodes[0].node.timer_tick_occurred();
417         check_added_monitors!(nodes[0], 1);
418
419         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
420         assert_eq!(events_0.len(), 1);
421         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
422                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
423                         (update_fee.as_ref().unwrap(), commitment_signed)
424                 },
425                 _ => panic!("Unexpected event"),
426         };
427
428         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
429         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
430         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
431         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
432         check_added_monitors!(nodes[1], 1);
433
434         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
435         // transaction:
436         {
437                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
438                 *feerate_lock = initial_feerate + 40;
439         }
440         nodes[0].node.timer_tick_occurred();
441         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
442         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
443
444         // Create the (3) update_fee message that nodes[0] will generate before it does...
445         let mut update_msg_2 = msgs::UpdateFee {
446                 channel_id: update_msg_1.channel_id.clone(),
447                 feerate_per_kw: (initial_feerate + 30) as u32,
448         };
449
450         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
451
452         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
453         // Deliver (3)
454         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
455
456         // Deliver (1), generating (3) and (4)
457         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
458         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
459         check_added_monitors!(nodes[0], 1);
460         assert!(as_second_update.update_add_htlcs.is_empty());
461         assert!(as_second_update.update_fulfill_htlcs.is_empty());
462         assert!(as_second_update.update_fail_htlcs.is_empty());
463         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
464         // Check that the update_fee newly generated matches what we delivered:
465         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
466         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
467
468         // Deliver (2) commitment_signed
469         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
470         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
471         check_added_monitors!(nodes[0], 1);
472         // No commitment_signed so get_event_msg's assert(len == 1) passes
473
474         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
475         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
476         check_added_monitors!(nodes[1], 1);
477
478         // Delever (4)
479         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
480         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
481         check_added_monitors!(nodes[1], 1);
482
483         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
484         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
485         check_added_monitors!(nodes[0], 1);
486
487         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
488         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
489         // No commitment_signed so get_event_msg's assert(len == 1) passes
490         check_added_monitors!(nodes[0], 1);
491
492         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
493         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
494         check_added_monitors!(nodes[1], 1);
495 }
496
497 fn do_test_sanity_on_in_flight_opens(steps: u8) {
498         // Previously, we had issues deserializing channels when we hadn't connected the first block
499         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
500         // serialization round-trips and simply do steps towards opening a channel and then drop the
501         // Node objects.
502
503         let chanmon_cfgs = create_chanmon_cfgs(2);
504         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
505         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
506         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
507
508         if steps & 0b1000_0000 != 0{
509                 let block = Block {
510                         header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
511                         txdata: vec![],
512                 };
513                 connect_block(&nodes[0], &block);
514                 connect_block(&nodes[1], &block);
515         }
516
517         if steps & 0x0f == 0 { return; }
518         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
519         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
520
521         if steps & 0x0f == 1 { return; }
522         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
523         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
524
525         if steps & 0x0f == 2 { return; }
526         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
527
528         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
529
530         if steps & 0x0f == 3 { return; }
531         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
532         check_added_monitors!(nodes[0], 0);
533         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
534
535         if steps & 0x0f == 4 { return; }
536         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
537         {
538                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
539                 assert_eq!(added_monitors.len(), 1);
540                 assert_eq!(added_monitors[0].0, funding_output);
541                 added_monitors.clear();
542         }
543         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
544
545         if steps & 0x0f == 5 { return; }
546         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
547         {
548                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
549                 assert_eq!(added_monitors.len(), 1);
550                 assert_eq!(added_monitors[0].0, funding_output);
551                 added_monitors.clear();
552         }
553
554         let events_4 = nodes[0].node.get_and_clear_pending_events();
555         assert_eq!(events_4.len(), 0);
556
557         if steps & 0x0f == 6 { return; }
558         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
559
560         if steps & 0x0f == 7 { return; }
561         confirm_transaction_at(&nodes[0], &tx, 2);
562         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
563         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
564         expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
565 }
566
567 #[test]
568 fn test_sanity_on_in_flight_opens() {
569         do_test_sanity_on_in_flight_opens(0);
570         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
571         do_test_sanity_on_in_flight_opens(1);
572         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
573         do_test_sanity_on_in_flight_opens(2);
574         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
575         do_test_sanity_on_in_flight_opens(3);
576         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
577         do_test_sanity_on_in_flight_opens(4);
578         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
579         do_test_sanity_on_in_flight_opens(5);
580         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
581         do_test_sanity_on_in_flight_opens(6);
582         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
583         do_test_sanity_on_in_flight_opens(7);
584         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
585         do_test_sanity_on_in_flight_opens(8);
586         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
587 }
588
589 #[test]
590 fn test_update_fee_vanilla() {
591         let chanmon_cfgs = create_chanmon_cfgs(2);
592         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
593         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
594         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
595         create_announced_chan_between_nodes(&nodes, 0, 1);
596
597         {
598                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
599                 *feerate_lock += 25;
600         }
601         nodes[0].node.timer_tick_occurred();
602         check_added_monitors!(nodes[0], 1);
603
604         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
605         assert_eq!(events_0.len(), 1);
606         let (update_msg, commitment_signed) = match events_0[0] {
607                         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 } } => {
608                         (update_fee.as_ref(), commitment_signed)
609                 },
610                 _ => panic!("Unexpected event"),
611         };
612         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
613
614         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
615         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
616         check_added_monitors!(nodes[1], 1);
617
618         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
619         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
620         check_added_monitors!(nodes[0], 1);
621
622         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
623         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
624         // No commitment_signed so get_event_msg's assert(len == 1) passes
625         check_added_monitors!(nodes[0], 1);
626
627         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
628         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
629         check_added_monitors!(nodes[1], 1);
630 }
631
632 #[test]
633 fn test_update_fee_that_funder_cannot_afford() {
634         let chanmon_cfgs = create_chanmon_cfgs(2);
635         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
636         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
637         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
638         let channel_value = 5000;
639         let push_sats = 700;
640         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000);
641         let channel_id = chan.2;
642         let secp_ctx = Secp256k1::new();
643         let default_config = UserConfig::default();
644         let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
645
646         let opt_anchors = false;
647
648         // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
649         // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
650         // calculate two different feerates here - the expected local limit as well as the expected
651         // remote limit.
652         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;
653         let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
654         {
655                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
656                 *feerate_lock = feerate;
657         }
658         nodes[0].node.timer_tick_occurred();
659         check_added_monitors!(nodes[0], 1);
660         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
661
662         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
663
664         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
665
666         // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
667         {
668                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
669
670                 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
671                 assert_eq!(commitment_tx.output.len(), 2);
672                 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
673                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
674                 actual_fee = channel_value - actual_fee;
675                 assert_eq!(total_fee, actual_fee);
676         }
677
678         {
679                 // Increment the feerate by a small constant, accounting for rounding errors
680                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
681                 *feerate_lock += 4;
682         }
683         nodes[0].node.timer_tick_occurred();
684         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
685         check_added_monitors!(nodes[0], 0);
686
687         const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
688
689         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
690         // needed to sign the new commitment tx and (2) sign the new commitment tx.
691         let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
692                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
693                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
694                 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
695                 let chan_signer = local_chan.get_signer();
696                 let pubkeys = chan_signer.pubkeys();
697                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
698                  pubkeys.funding_pubkey)
699         };
700         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
701                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
702                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
703                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
704                 let chan_signer = remote_chan.get_signer();
705                 let pubkeys = chan_signer.pubkeys();
706                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
707                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
708                  pubkeys.funding_pubkey)
709         };
710
711         // Assemble the set of keys we can use for signatures for our commitment_signed message.
712         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
713                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
714
715         let res = {
716                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
717                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
718                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
719                 let local_chan_signer = local_chan.get_signer();
720                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
721                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
722                         INITIAL_COMMITMENT_NUMBER - 1,
723                         push_sats,
724                         channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
725                         opt_anchors, local_funding, remote_funding,
726                         commit_tx_keys.clone(),
727                         non_buffer_feerate + 4,
728                         &mut htlcs,
729                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
730                 );
731                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
732         };
733
734         let commit_signed_msg = msgs::CommitmentSigned {
735                 channel_id: chan.2,
736                 signature: res.0,
737                 htlc_signatures: res.1
738         };
739
740         let update_fee = msgs::UpdateFee {
741                 channel_id: chan.2,
742                 feerate_per_kw: non_buffer_feerate + 4,
743         };
744
745         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
746
747         //While producing the commitment_signed response after handling a received update_fee request the
748         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
749         //Should produce and error.
750         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
751         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
752         check_added_monitors!(nodes[1], 1);
753         check_closed_broadcast!(nodes[1], true);
754         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
755 }
756
757 #[test]
758 fn test_update_fee_with_fundee_update_add_htlc() {
759         let chanmon_cfgs = create_chanmon_cfgs(2);
760         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
761         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
762         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
763         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
764
765         // balancing
766         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
767
768         {
769                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
770                 *feerate_lock += 20;
771         }
772         nodes[0].node.timer_tick_occurred();
773         check_added_monitors!(nodes[0], 1);
774
775         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
776         assert_eq!(events_0.len(), 1);
777         let (update_msg, commitment_signed) = match events_0[0] {
778                         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 } } => {
779                         (update_fee.as_ref(), commitment_signed)
780                 },
781                 _ => panic!("Unexpected event"),
782         };
783         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
784         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
785         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
786         check_added_monitors!(nodes[1], 1);
787
788         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
789
790         // nothing happens since node[1] is in AwaitingRemoteRevoke
791         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
792         {
793                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
794                 assert_eq!(added_monitors.len(), 0);
795                 added_monitors.clear();
796         }
797         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
798         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
799         // node[1] has nothing to do
800
801         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
802         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
803         check_added_monitors!(nodes[0], 1);
804
805         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
806         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
807         // No commitment_signed so get_event_msg's assert(len == 1) passes
808         check_added_monitors!(nodes[0], 1);
809         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
810         check_added_monitors!(nodes[1], 1);
811         // AwaitingRemoteRevoke ends here
812
813         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
814         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
815         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
816         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
817         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
818         assert_eq!(commitment_update.update_fee.is_none(), true);
819
820         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
821         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
822         check_added_monitors!(nodes[0], 1);
823         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
824
825         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
826         check_added_monitors!(nodes[1], 1);
827         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
828
829         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
830         check_added_monitors!(nodes[1], 1);
831         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
832         // No commitment_signed so get_event_msg's assert(len == 1) passes
833
834         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
835         check_added_monitors!(nodes[0], 1);
836         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
837
838         expect_pending_htlcs_forwardable!(nodes[0]);
839
840         let events = nodes[0].node.get_and_clear_pending_events();
841         assert_eq!(events.len(), 1);
842         match events[0] {
843                 Event::PaymentClaimable { .. } => { },
844                 _ => panic!("Unexpected event"),
845         };
846
847         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
848
849         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
850         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
851         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
852         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
853         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
854 }
855
856 #[test]
857 fn test_update_fee() {
858         let chanmon_cfgs = create_chanmon_cfgs(2);
859         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
860         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
861         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
862         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
863         let channel_id = chan.2;
864
865         // A                                        B
866         // (1) update_fee/commitment_signed      ->
867         //                                       <- (2) revoke_and_ack
868         //                                       .- send (3) commitment_signed
869         // (4) update_fee/commitment_signed      ->
870         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
871         //                                       <- (3) commitment_signed delivered
872         // send (6) revoke_and_ack               -.
873         //                                       <- (5) deliver revoke_and_ack
874         // (6) deliver revoke_and_ack            ->
875         //                                       .- send (7) commitment_signed in response to (4)
876         //                                       <- (7) deliver commitment_signed
877         // revoke_and_ack                        ->
878
879         // Create and deliver (1)...
880         let feerate;
881         {
882                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
883                 feerate = *feerate_lock;
884                 *feerate_lock = feerate + 20;
885         }
886         nodes[0].node.timer_tick_occurred();
887         check_added_monitors!(nodes[0], 1);
888
889         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
890         assert_eq!(events_0.len(), 1);
891         let (update_msg, commitment_signed) = match events_0[0] {
892                         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 } } => {
893                         (update_fee.as_ref(), commitment_signed)
894                 },
895                 _ => panic!("Unexpected event"),
896         };
897         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
898
899         // Generate (2) and (3):
900         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
901         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
902         check_added_monitors!(nodes[1], 1);
903
904         // Deliver (2):
905         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
906         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
907         check_added_monitors!(nodes[0], 1);
908
909         // Create and deliver (4)...
910         {
911                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
912                 *feerate_lock = feerate + 30;
913         }
914         nodes[0].node.timer_tick_occurred();
915         check_added_monitors!(nodes[0], 1);
916         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
917         assert_eq!(events_0.len(), 1);
918         let (update_msg, commitment_signed) = match events_0[0] {
919                         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 } } => {
920                         (update_fee.as_ref(), commitment_signed)
921                 },
922                 _ => panic!("Unexpected event"),
923         };
924
925         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
926         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
927         check_added_monitors!(nodes[1], 1);
928         // ... creating (5)
929         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
930         // No commitment_signed so get_event_msg's assert(len == 1) passes
931
932         // Handle (3), creating (6):
933         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
934         check_added_monitors!(nodes[0], 1);
935         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
936         // No commitment_signed so get_event_msg's assert(len == 1) passes
937
938         // Deliver (5):
939         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
940         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
941         check_added_monitors!(nodes[0], 1);
942
943         // Deliver (6), creating (7):
944         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
945         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
946         assert!(commitment_update.update_add_htlcs.is_empty());
947         assert!(commitment_update.update_fulfill_htlcs.is_empty());
948         assert!(commitment_update.update_fail_htlcs.is_empty());
949         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
950         assert!(commitment_update.update_fee.is_none());
951         check_added_monitors!(nodes[1], 1);
952
953         // Deliver (7)
954         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
955         check_added_monitors!(nodes[0], 1);
956         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
957         // No commitment_signed so get_event_msg's assert(len == 1) passes
958
959         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
960         check_added_monitors!(nodes[1], 1);
961         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
962
963         assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
964         assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
965         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
966         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
967         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
968 }
969
970 #[test]
971 fn fake_network_test() {
972         // Simple test which builds a network of ChannelManagers, connects them to each other, and
973         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
974         let chanmon_cfgs = create_chanmon_cfgs(4);
975         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
976         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
977         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
978
979         // Create some initial channels
980         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
981         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
982         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
983
984         // Rebalance the network a bit by relaying one payment through all the channels...
985         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
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
990         // Send some more payments
991         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
992         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
993         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
994
995         // Test failure packets
996         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
997         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
998
999         // Add a new channel that skips 3
1000         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1001
1002         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1003         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1004         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
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
1010         // Do some rebalance loop payments, simultaneously
1011         let mut hops = Vec::with_capacity(3);
1012         hops.push(RouteHop {
1013                 pubkey: nodes[2].node.get_our_node_id(),
1014                 node_features: NodeFeatures::empty(),
1015                 short_channel_id: chan_2.0.contents.short_channel_id,
1016                 channel_features: ChannelFeatures::empty(),
1017                 fee_msat: 0,
1018                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1019         });
1020         hops.push(RouteHop {
1021                 pubkey: nodes[3].node.get_our_node_id(),
1022                 node_features: NodeFeatures::empty(),
1023                 short_channel_id: chan_3.0.contents.short_channel_id,
1024                 channel_features: ChannelFeatures::empty(),
1025                 fee_msat: 0,
1026                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1027         });
1028         hops.push(RouteHop {
1029                 pubkey: nodes[1].node.get_our_node_id(),
1030                 node_features: nodes[1].node.node_features(),
1031                 short_channel_id: chan_4.0.contents.short_channel_id,
1032                 channel_features: nodes[1].node.channel_features(),
1033                 fee_msat: 1000000,
1034                 cltv_expiry_delta: TEST_FINAL_CLTV,
1035         });
1036         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;
1037         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;
1038         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;
1039
1040         let mut hops = Vec::with_capacity(3);
1041         hops.push(RouteHop {
1042                 pubkey: nodes[3].node.get_our_node_id(),
1043                 node_features: NodeFeatures::empty(),
1044                 short_channel_id: chan_4.0.contents.short_channel_id,
1045                 channel_features: ChannelFeatures::empty(),
1046                 fee_msat: 0,
1047                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1048         });
1049         hops.push(RouteHop {
1050                 pubkey: nodes[2].node.get_our_node_id(),
1051                 node_features: NodeFeatures::empty(),
1052                 short_channel_id: chan_3.0.contents.short_channel_id,
1053                 channel_features: ChannelFeatures::empty(),
1054                 fee_msat: 0,
1055                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1056         });
1057         hops.push(RouteHop {
1058                 pubkey: nodes[1].node.get_our_node_id(),
1059                 node_features: nodes[1].node.node_features(),
1060                 short_channel_id: chan_2.0.contents.short_channel_id,
1061                 channel_features: nodes[1].node.channel_features(),
1062                 fee_msat: 1000000,
1063                 cltv_expiry_delta: TEST_FINAL_CLTV,
1064         });
1065         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;
1066         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;
1067         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;
1068
1069         // Claim the rebalances...
1070         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1071         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1072
1073         // Close down the channels...
1074         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1075         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1076         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1077         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1078         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1079         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1080         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1081         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1082         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1083         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1084         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1085         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1086 }
1087
1088 #[test]
1089 fn holding_cell_htlc_counting() {
1090         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1091         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1092         // commitment dance rounds.
1093         let chanmon_cfgs = create_chanmon_cfgs(3);
1094         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1095         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1096         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1097         create_announced_chan_between_nodes(&nodes, 0, 1);
1098         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1099
1100         let mut payments = Vec::new();
1101         for _ in 0..crate::ln::channel::OUR_MAX_HTLCS {
1102                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1103                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
1104                 payments.push((payment_preimage, payment_hash));
1105         }
1106         check_added_monitors!(nodes[1], 1);
1107
1108         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1109         assert_eq!(events.len(), 1);
1110         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1111         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1112
1113         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1114         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1115         // another HTLC.
1116         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1117         {
1118                 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 },
1119                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1120                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1121                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1122         }
1123
1124         // This should also be true if we try to forward a payment.
1125         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1126         {
1127                 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1128                 check_added_monitors!(nodes[0], 1);
1129         }
1130
1131         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1132         assert_eq!(events.len(), 1);
1133         let payment_event = SendEvent::from_event(events.pop().unwrap());
1134         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1135
1136         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1137         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1138         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1139         // fails), the second will process the resulting failure and fail the HTLC backward.
1140         expect_pending_htlcs_forwardable!(nodes[1]);
1141         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 }]);
1142         check_added_monitors!(nodes[1], 1);
1143
1144         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1145         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1146         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1147
1148         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1149
1150         // Now forward all the pending HTLCs and claim them back
1151         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1152         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1153         check_added_monitors!(nodes[2], 1);
1154
1155         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1156         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1157         check_added_monitors!(nodes[1], 1);
1158         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1159
1160         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1161         check_added_monitors!(nodes[1], 1);
1162         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1163
1164         for ref update in as_updates.update_add_htlcs.iter() {
1165                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1166         }
1167         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1168         check_added_monitors!(nodes[2], 1);
1169         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1170         check_added_monitors!(nodes[2], 1);
1171         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1172
1173         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1174         check_added_monitors!(nodes[1], 1);
1175         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1176         check_added_monitors!(nodes[1], 1);
1177         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1178
1179         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1180         check_added_monitors!(nodes[2], 1);
1181
1182         expect_pending_htlcs_forwardable!(nodes[2]);
1183
1184         let events = nodes[2].node.get_and_clear_pending_events();
1185         assert_eq!(events.len(), payments.len());
1186         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1187                 match event {
1188                         &Event::PaymentClaimable { ref payment_hash, .. } => {
1189                                 assert_eq!(*payment_hash, *hash);
1190                         },
1191                         _ => panic!("Unexpected event"),
1192                 };
1193         }
1194
1195         for (preimage, _) in payments.drain(..) {
1196                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1197         }
1198
1199         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1200 }
1201
1202 #[test]
1203 fn duplicate_htlc_test() {
1204         // Test that we accept duplicate payment_hash HTLCs across the network and that
1205         // claiming/failing them are all separate and don't affect each other
1206         let chanmon_cfgs = create_chanmon_cfgs(6);
1207         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1208         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1209         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1210
1211         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1212         create_announced_chan_between_nodes(&nodes, 0, 3);
1213         create_announced_chan_between_nodes(&nodes, 1, 3);
1214         create_announced_chan_between_nodes(&nodes, 2, 3);
1215         create_announced_chan_between_nodes(&nodes, 3, 4);
1216         create_announced_chan_between_nodes(&nodes, 3, 5);
1217
1218         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1219
1220         *nodes[0].network_payment_count.borrow_mut() -= 1;
1221         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1222
1223         *nodes[0].network_payment_count.borrow_mut() -= 1;
1224         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1225
1226         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1227         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1228         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1229 }
1230
1231 #[test]
1232 fn test_duplicate_htlc_different_direction_onchain() {
1233         // Test that ChannelMonitor doesn't generate 2 preimage txn
1234         // when we have 2 HTLCs with same preimage that go across a node
1235         // in opposite directions, even with the same payment secret.
1236         let chanmon_cfgs = create_chanmon_cfgs(2);
1237         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1238         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1239         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1240
1241         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1242
1243         // balancing
1244         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1245
1246         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1247
1248         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1249         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1250         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1251
1252         // Provide preimage to node 0 by claiming payment
1253         nodes[0].node.claim_funds(payment_preimage);
1254         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1255         check_added_monitors!(nodes[0], 1);
1256
1257         // Broadcast node 1 commitment txn
1258         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1259
1260         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1261         let mut has_both_htlcs = 0; // check htlcs match ones committed
1262         for outp in remote_txn[0].output.iter() {
1263                 if outp.value == 800_000 / 1000 {
1264                         has_both_htlcs += 1;
1265                 } else if outp.value == 900_000 / 1000 {
1266                         has_both_htlcs += 1;
1267                 }
1268         }
1269         assert_eq!(has_both_htlcs, 2);
1270
1271         mine_transaction(&nodes[0], &remote_txn[0]);
1272         check_added_monitors!(nodes[0], 1);
1273         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1274         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1275
1276         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1277         assert_eq!(claim_txn.len(), 3);
1278
1279         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1280         check_spends!(claim_txn[1], remote_txn[0]);
1281         check_spends!(claim_txn[2], remote_txn[0]);
1282         let preimage_tx = &claim_txn[0];
1283         let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1284                 (&claim_txn[1], &claim_txn[2])
1285         } else {
1286                 (&claim_txn[2], &claim_txn[1])
1287         };
1288
1289         assert_eq!(preimage_tx.input.len(), 1);
1290         assert_eq!(preimage_bump_tx.input.len(), 1);
1291
1292         assert_eq!(preimage_tx.input.len(), 1);
1293         assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1294         assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1295
1296         assert_eq!(timeout_tx.input.len(), 1);
1297         assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1298         check_spends!(timeout_tx, remote_txn[0]);
1299         assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1300
1301         let events = nodes[0].node.get_and_clear_pending_msg_events();
1302         assert_eq!(events.len(), 3);
1303         for e in events {
1304                 match e {
1305                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1306                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1307                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1308                                 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1309                         },
1310                         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, .. } } => {
1311                                 assert!(update_add_htlcs.is_empty());
1312                                 assert!(update_fail_htlcs.is_empty());
1313                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1314                                 assert!(update_fail_malformed_htlcs.is_empty());
1315                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1316                         },
1317                         _ => panic!("Unexpected event"),
1318                 }
1319         }
1320 }
1321
1322 #[test]
1323 fn test_basic_channel_reserve() {
1324         let chanmon_cfgs = create_chanmon_cfgs(2);
1325         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1326         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1327         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1328         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1329
1330         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1331         let channel_reserve = chan_stat.channel_reserve_msat;
1332
1333         // The 2* and +1 are for the fee spike reserve.
1334         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));
1335         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1336         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1337         let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1338         match err {
1339                 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1340                         match &fails[0] {
1341                                 &APIError::ChannelUnavailable{ref err} =>
1342                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1343                                 _ => panic!("Unexpected error variant"),
1344                         }
1345                 },
1346                 _ => panic!("Unexpected error variant"),
1347         }
1348         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1349         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1350
1351         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1352 }
1353
1354 #[test]
1355 fn test_fee_spike_violation_fails_htlc() {
1356         let chanmon_cfgs = create_chanmon_cfgs(2);
1357         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1358         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1359         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1360         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1361
1362         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1363         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1364         let secp_ctx = Secp256k1::new();
1365         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1366
1367         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1368
1369         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1370         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1371         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1372         let msg = msgs::UpdateAddHTLC {
1373                 channel_id: chan.2,
1374                 htlc_id: 0,
1375                 amount_msat: htlc_msat,
1376                 payment_hash: payment_hash,
1377                 cltv_expiry: htlc_cltv,
1378                 onion_routing_packet: onion_packet,
1379         };
1380
1381         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1382
1383         // Now manually create the commitment_signed message corresponding to the update_add
1384         // nodes[0] just sent. In the code for construction of this message, "local" refers
1385         // to the sender of the message, and "remote" refers to the receiver.
1386
1387         let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1388
1389         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1390
1391         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1392         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1393         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1394                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1395                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1396                 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1397                 let chan_signer = local_chan.get_signer();
1398                 // Make the signer believe we validated another commitment, so we can release the secret
1399                 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1400
1401                 let pubkeys = chan_signer.pubkeys();
1402                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1403                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1404                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1405                  chan_signer.pubkeys().funding_pubkey)
1406         };
1407         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1408                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1409                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1410                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1411                 let chan_signer = remote_chan.get_signer();
1412                 let pubkeys = chan_signer.pubkeys();
1413                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1414                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1415                  chan_signer.pubkeys().funding_pubkey)
1416         };
1417
1418         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1419         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1420                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1421
1422         // Build the remote commitment transaction so we can sign it, and then later use the
1423         // signature for the commitment_signed message.
1424         let local_chan_balance = 1313;
1425
1426         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1427                 offered: false,
1428                 amount_msat: 3460001,
1429                 cltv_expiry: htlc_cltv,
1430                 payment_hash,
1431                 transaction_output_index: Some(1),
1432         };
1433
1434         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1435
1436         let res = {
1437                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1438                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1439                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
1440                 let local_chan_signer = local_chan.get_signer();
1441                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1442                         commitment_number,
1443                         95000,
1444                         local_chan_balance,
1445                         local_chan.opt_anchors(), local_funding, remote_funding,
1446                         commit_tx_keys.clone(),
1447                         feerate_per_kw,
1448                         &mut vec![(accepted_htlc_info, ())],
1449                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1450                 );
1451                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1452         };
1453
1454         let commit_signed_msg = msgs::CommitmentSigned {
1455                 channel_id: chan.2,
1456                 signature: res.0,
1457                 htlc_signatures: res.1
1458         };
1459
1460         // Send the commitment_signed message to the nodes[1].
1461         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1462         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1463
1464         // Send the RAA to nodes[1].
1465         let raa_msg = msgs::RevokeAndACK {
1466                 channel_id: chan.2,
1467                 per_commitment_secret: local_secret,
1468                 next_per_commitment_point: next_local_point
1469         };
1470         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1471
1472         let events = nodes[1].node.get_and_clear_pending_msg_events();
1473         assert_eq!(events.len(), 1);
1474         // Make sure the HTLC failed in the way we expect.
1475         match events[0] {
1476                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1477                         assert_eq!(update_fail_htlcs.len(), 1);
1478                         update_fail_htlcs[0].clone()
1479                 },
1480                 _ => panic!("Unexpected event"),
1481         };
1482         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1483                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1484
1485         check_added_monitors!(nodes[1], 2);
1486 }
1487
1488 #[test]
1489 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1490         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1491         // Set the fee rate for the channel very high, to the point where the fundee
1492         // sending any above-dust amount would result in a channel reserve violation.
1493         // In this test we check that we would be prevented from sending an HTLC in
1494         // this situation.
1495         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1496         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1497         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1498         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1499         let default_config = UserConfig::default();
1500         let opt_anchors = false;
1501
1502         let mut push_amt = 100_000_000;
1503         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1504
1505         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1506
1507         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1508
1509         // Sending exactly enough to hit the reserve amount should be accepted
1510         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1511                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1512         }
1513
1514         // However one more HTLC should be significantly over the reserve amount and fail.
1515         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1516         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 },
1517                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1518         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1519         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);
1520 }
1521
1522 #[test]
1523 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1524         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1525         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1526         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1527         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1528         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1529         let default_config = UserConfig::default();
1530         let opt_anchors = false;
1531
1532         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1533         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1534         // transaction fee with 0 HTLCs (183 sats)).
1535         let mut push_amt = 100_000_000;
1536         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1537         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1538         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1539
1540         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1541         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1542                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1543         }
1544
1545         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1546         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1547         let secp_ctx = Secp256k1::new();
1548         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1549         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1550         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1551         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1552         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1553         let msg = msgs::UpdateAddHTLC {
1554                 channel_id: chan.2,
1555                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1556                 amount_msat: htlc_msat,
1557                 payment_hash: payment_hash,
1558                 cltv_expiry: htlc_cltv,
1559                 onion_routing_packet: onion_packet,
1560         };
1561
1562         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1563         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1564         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);
1565         assert_eq!(nodes[0].node.list_channels().len(), 0);
1566         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1567         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1568         check_added_monitors!(nodes[0], 1);
1569         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() });
1570 }
1571
1572 #[test]
1573 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1574         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1575         // calculating our commitment transaction fee (this was previously broken).
1576         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1577         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1578
1579         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1580         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1581         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1582         let default_config = UserConfig::default();
1583         let opt_anchors = false;
1584
1585         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1586         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1587         // transaction fee with 0 HTLCs (183 sats)).
1588         let mut push_amt = 100_000_000;
1589         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1590         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1591         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1592
1593         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1594                 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1595         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1596         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1597         // commitment transaction fee.
1598         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1599
1600         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1601         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1602                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1603         }
1604
1605         // One more than the dust amt should fail, however.
1606         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1607         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 },
1608                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1609 }
1610
1611 #[test]
1612 fn test_chan_init_feerate_unaffordability() {
1613         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1614         // channel reserve and feerate requirements.
1615         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1616         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1617         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1618         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1619         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1620         let default_config = UserConfig::default();
1621         let opt_anchors = false;
1622
1623         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1624         // HTLC.
1625         let mut push_amt = 100_000_000;
1626         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1627         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1628                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1629
1630         // During open, we don't have a "counterparty channel reserve" to check against, so that
1631         // requirement only comes into play on the open_channel handling side.
1632         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1633         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1634         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1635         open_channel_msg.push_msat += 1;
1636         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1637
1638         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1639         assert_eq!(msg_events.len(), 1);
1640         match msg_events[0] {
1641                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1642                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1643                 },
1644                 _ => panic!("Unexpected event"),
1645         }
1646 }
1647
1648 #[test]
1649 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1650         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1651         // calculating our counterparty's commitment transaction fee (this was previously broken).
1652         let chanmon_cfgs = create_chanmon_cfgs(2);
1653         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1654         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1655         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1656         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1657
1658         let payment_amt = 46000; // Dust amount
1659         // In the previous code, these first four payments would succeed.
1660         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
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
1665         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1666         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1667         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1668         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1669         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1670         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1671
1672         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1673         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1674         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1675         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1676 }
1677
1678 #[test]
1679 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1680         let chanmon_cfgs = create_chanmon_cfgs(3);
1681         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1682         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1683         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1684         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1685         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1686
1687         let feemsat = 239;
1688         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1689         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1690         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1691         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
1692
1693         // Add a 2* and +1 for the fee spike reserve.
1694         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1695         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;
1696         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1697
1698         // Add a pending HTLC.
1699         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1700         let payment_event_1 = {
1701                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1702                 check_added_monitors!(nodes[0], 1);
1703
1704                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1705                 assert_eq!(events.len(), 1);
1706                 SendEvent::from_event(events.remove(0))
1707         };
1708         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1709
1710         // Attempt to trigger a channel reserve violation --> payment failure.
1711         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1712         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;
1713         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1714         let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1715
1716         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1717         let secp_ctx = Secp256k1::new();
1718         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1719         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1720         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1721         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1722         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1723         let msg = msgs::UpdateAddHTLC {
1724                 channel_id: chan.2,
1725                 htlc_id: 1,
1726                 amount_msat: htlc_msat + 1,
1727                 payment_hash: our_payment_hash_1,
1728                 cltv_expiry: htlc_cltv,
1729                 onion_routing_packet: onion_packet,
1730         };
1731
1732         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1733         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1734         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1735         assert_eq!(nodes[1].node.list_channels().len(), 1);
1736         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1737         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1738         check_added_monitors!(nodes[1], 1);
1739         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1740 }
1741
1742 #[test]
1743 fn test_inbound_outbound_capacity_is_not_zero() {
1744         let chanmon_cfgs = create_chanmon_cfgs(2);
1745         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1746         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1747         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1748         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1749         let channels0 = node_chanmgrs[0].list_channels();
1750         let channels1 = node_chanmgrs[1].list_channels();
1751         let default_config = UserConfig::default();
1752         assert_eq!(channels0.len(), 1);
1753         assert_eq!(channels1.len(), 1);
1754
1755         let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1756         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1757         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1758
1759         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1760         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1761 }
1762
1763 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1764         (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1765 }
1766
1767 #[test]
1768 fn test_channel_reserve_holding_cell_htlcs() {
1769         let chanmon_cfgs = create_chanmon_cfgs(3);
1770         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1771         // When this test was written, the default base fee floated based on the HTLC count.
1772         // It is now fixed, so we simply set the fee to the expected value here.
1773         let mut config = test_default_channel_config();
1774         config.channel_config.forwarding_fee_base_msat = 239;
1775         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1776         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1777         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1778         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1779
1780         let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1781         let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1782
1783         let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1784         let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1785
1786         macro_rules! expect_forward {
1787                 ($node: expr) => {{
1788                         let mut events = $node.node.get_and_clear_pending_msg_events();
1789                         assert_eq!(events.len(), 1);
1790                         check_added_monitors!($node, 1);
1791                         let payment_event = SendEvent::from_event(events.remove(0));
1792                         payment_event
1793                 }}
1794         }
1795
1796         let feemsat = 239; // set above
1797         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1798         let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1799         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_1.2);
1800
1801         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1802
1803         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1804         {
1805                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1806                         .with_features(nodes[2].node.invoice_features()).with_max_channel_saturation_power_of_half(0);
1807                 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);
1808                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1809                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1810
1811                 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 },
1812                         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)));
1813                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1814                 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over the max HTLC value in flight our peer will accept".to_string(), 1);
1815         }
1816
1817         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1818         // nodes[0]'s wealth
1819         loop {
1820                 let amt_msat = recv_value_0 + total_fee_msat;
1821                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1822                 // Also, ensure that each payment has enough to be over the dust limit to
1823                 // ensure it'll be included in each commit tx fee calculation.
1824                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1825                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1826                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1827                         break;
1828                 }
1829
1830                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1831                         .with_features(nodes[2].node.invoice_features()).with_max_channel_saturation_power_of_half(0);
1832                 let route = get_route!(nodes[0], payment_params, recv_value_0, TEST_FINAL_CLTV).unwrap();
1833                 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1834                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1835
1836                 let (stat01_, stat11_, stat12_, stat22_) = (
1837                         get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1838                         get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1839                         get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1840                         get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1841                 );
1842
1843                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1844                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1845                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1846                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1847                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1848         }
1849
1850         // adding pending output.
1851         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1852         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1853         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1854         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1855         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1856         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1857         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1858         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1859         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1860         // policy.
1861         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1862         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1863         let amt_msat_1 = recv_value_1 + total_fee_msat;
1864
1865         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);
1866         let payment_event_1 = {
1867                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1868                 check_added_monitors!(nodes[0], 1);
1869
1870                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1871                 assert_eq!(events.len(), 1);
1872                 SendEvent::from_event(events.remove(0))
1873         };
1874         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1875
1876         // channel reserve test with htlc pending output > 0
1877         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1878         {
1879                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1880                 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 },
1881                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1882                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1883         }
1884
1885         // split the rest to test holding cell
1886         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1887         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1888         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1889         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1890         {
1891                 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1892                 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);
1893         }
1894
1895         // now see if they go through on both sides
1896         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);
1897         // but this will stuck in the holding cell
1898         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1899         check_added_monitors!(nodes[0], 0);
1900         let events = nodes[0].node.get_and_clear_pending_events();
1901         assert_eq!(events.len(), 0);
1902
1903         // test with outbound holding cell amount > 0
1904         {
1905                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1906                 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 },
1907                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1908                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1909                 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put our balance under counterparty-announced channel reserve value".to_string(), 2);
1910         }
1911
1912         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);
1913         // this will also stuck in the holding cell
1914         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1915         check_added_monitors!(nodes[0], 0);
1916         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1917         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1918
1919         // flush the pending htlc
1920         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1921         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1922         check_added_monitors!(nodes[1], 1);
1923
1924         // the pending htlc should be promoted to committed
1925         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1926         check_added_monitors!(nodes[0], 1);
1927         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1928
1929         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1930         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1931         // No commitment_signed so get_event_msg's assert(len == 1) passes
1932         check_added_monitors!(nodes[0], 1);
1933
1934         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1935         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1936         check_added_monitors!(nodes[1], 1);
1937
1938         expect_pending_htlcs_forwardable!(nodes[1]);
1939
1940         let ref payment_event_11 = expect_forward!(nodes[1]);
1941         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1942         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1943
1944         expect_pending_htlcs_forwardable!(nodes[2]);
1945         expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1946
1947         // flush the htlcs in the holding cell
1948         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1949         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1950         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1951         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1952         expect_pending_htlcs_forwardable!(nodes[1]);
1953
1954         let ref payment_event_3 = expect_forward!(nodes[1]);
1955         assert_eq!(payment_event_3.msgs.len(), 2);
1956         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1957         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1958
1959         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1960         expect_pending_htlcs_forwardable!(nodes[2]);
1961
1962         let events = nodes[2].node.get_and_clear_pending_events();
1963         assert_eq!(events.len(), 2);
1964         match events[0] {
1965                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
1966                         assert_eq!(our_payment_hash_21, *payment_hash);
1967                         assert_eq!(recv_value_21, amount_msat);
1968                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
1969                         assert_eq!(via_channel_id, Some(chan_2.2));
1970                         match &purpose {
1971                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1972                                         assert!(payment_preimage.is_none());
1973                                         assert_eq!(our_payment_secret_21, *payment_secret);
1974                                 },
1975                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1976                         }
1977                 },
1978                 _ => panic!("Unexpected event"),
1979         }
1980         match events[1] {
1981                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
1982                         assert_eq!(our_payment_hash_22, *payment_hash);
1983                         assert_eq!(recv_value_22, amount_msat);
1984                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
1985                         assert_eq!(via_channel_id, Some(chan_2.2));
1986                         match &purpose {
1987                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1988                                         assert!(payment_preimage.is_none());
1989                                         assert_eq!(our_payment_secret_22, *payment_secret);
1990                                 },
1991                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1992                         }
1993                 },
1994                 _ => panic!("Unexpected event"),
1995         }
1996
1997         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1998         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1999         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2000
2001         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2002         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2003         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2004
2005         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2006         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);
2007         let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2008         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2009         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2010
2011         let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2012         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2013 }
2014
2015 #[test]
2016 fn channel_reserve_in_flight_removes() {
2017         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2018         // can send to its counterparty, but due to update ordering, the other side may not yet have
2019         // considered those HTLCs fully removed.
2020         // This tests that we don't count HTLCs which will not be included in the next remote
2021         // commitment transaction towards the reserve value (as it implies no commitment transaction
2022         // will be generated which violates the remote reserve value).
2023         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2024         // To test this we:
2025         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2026         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2027         //    you only consider the value of the first HTLC, it may not),
2028         //  * start routing a third HTLC from A to B,
2029         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2030         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2031         //  * deliver the first fulfill from B
2032         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2033         //    claim,
2034         //  * deliver A's response CS and RAA.
2035         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2036         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2037         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2038         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2039         let chanmon_cfgs = create_chanmon_cfgs(2);
2040         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2041         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2042         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2043         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2044
2045         let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2046         // Route the first two HTLCs.
2047         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2048         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2049         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2050
2051         // Start routing the third HTLC (this is just used to get everyone in the right state).
2052         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2053         let send_1 = {
2054                 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2055                 check_added_monitors!(nodes[0], 1);
2056                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2057                 assert_eq!(events.len(), 1);
2058                 SendEvent::from_event(events.remove(0))
2059         };
2060
2061         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2062         // initial fulfill/CS.
2063         nodes[1].node.claim_funds(payment_preimage_1);
2064         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2065         check_added_monitors!(nodes[1], 1);
2066         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2067
2068         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2069         // remove the second HTLC when we send the HTLC back from B to A.
2070         nodes[1].node.claim_funds(payment_preimage_2);
2071         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2072         check_added_monitors!(nodes[1], 1);
2073         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2074
2075         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2076         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2077         check_added_monitors!(nodes[0], 1);
2078         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2079         expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2080
2081         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2082         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2083         check_added_monitors!(nodes[1], 1);
2084         // B is already AwaitingRAA, so cant generate a CS here
2085         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2086
2087         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2088         check_added_monitors!(nodes[1], 1);
2089         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2090
2091         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2092         check_added_monitors!(nodes[0], 1);
2093         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2094
2095         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2096         check_added_monitors!(nodes[1], 1);
2097         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2098
2099         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2100         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2101         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2102         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2103         // on-chain as necessary).
2104         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2105         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2106         check_added_monitors!(nodes[0], 1);
2107         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2108         expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2109
2110         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2111         check_added_monitors!(nodes[1], 1);
2112         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2113
2114         expect_pending_htlcs_forwardable!(nodes[1]);
2115         expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2116
2117         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2118         // resolve the second HTLC from A's point of view.
2119         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2120         check_added_monitors!(nodes[0], 1);
2121         expect_payment_path_successful!(nodes[0]);
2122         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2123
2124         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2125         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2126         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2127         let send_2 = {
2128                 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2129                 check_added_monitors!(nodes[1], 1);
2130                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2131                 assert_eq!(events.len(), 1);
2132                 SendEvent::from_event(events.remove(0))
2133         };
2134
2135         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2136         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2137         check_added_monitors!(nodes[0], 1);
2138         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2139
2140         // Now just resolve all the outstanding messages/HTLCs for completeness...
2141
2142         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2143         check_added_monitors!(nodes[1], 1);
2144         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2145
2146         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2147         check_added_monitors!(nodes[1], 1);
2148
2149         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2150         check_added_monitors!(nodes[0], 1);
2151         expect_payment_path_successful!(nodes[0]);
2152         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2153
2154         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2155         check_added_monitors!(nodes[1], 1);
2156         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2157
2158         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2159         check_added_monitors!(nodes[0], 1);
2160
2161         expect_pending_htlcs_forwardable!(nodes[0]);
2162         expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2163
2164         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2165         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2166 }
2167
2168 #[test]
2169 fn channel_monitor_network_test() {
2170         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2171         // tests that ChannelMonitor is able to recover from various states.
2172         let chanmon_cfgs = create_chanmon_cfgs(5);
2173         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2174         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2175         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2176
2177         // Create some initial channels
2178         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2179         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2180         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2181         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2182
2183         // Make sure all nodes are at the same starting height
2184         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2185         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2186         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2187         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2188         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2189
2190         // Rebalance the network a bit by relaying one payment through all the channels...
2191         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
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
2196         // Simple case with no pending HTLCs:
2197         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2198         check_added_monitors!(nodes[1], 1);
2199         check_closed_broadcast!(nodes[1], true);
2200         {
2201                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2202                 assert_eq!(node_txn.len(), 1);
2203                 mine_transaction(&nodes[0], &node_txn[0]);
2204                 check_added_monitors!(nodes[0], 1);
2205                 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2206         }
2207         check_closed_broadcast!(nodes[0], true);
2208         assert_eq!(nodes[0].node.list_channels().len(), 0);
2209         assert_eq!(nodes[1].node.list_channels().len(), 1);
2210         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2211         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2212
2213         // One pending HTLC is discarded by the force-close:
2214         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2215
2216         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2217         // broadcasted until we reach the timelock time).
2218         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2219         check_closed_broadcast!(nodes[1], true);
2220         check_added_monitors!(nodes[1], 1);
2221         {
2222                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2223                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2224                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2225                 mine_transaction(&nodes[2], &node_txn[0]);
2226                 check_added_monitors!(nodes[2], 1);
2227                 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2228         }
2229         check_closed_broadcast!(nodes[2], true);
2230         assert_eq!(nodes[1].node.list_channels().len(), 0);
2231         assert_eq!(nodes[2].node.list_channels().len(), 1);
2232         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2233         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2234
2235         macro_rules! claim_funds {
2236                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2237                         {
2238                                 $node.node.claim_funds($preimage);
2239                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2240                                 check_added_monitors!($node, 1);
2241
2242                                 let events = $node.node.get_and_clear_pending_msg_events();
2243                                 assert_eq!(events.len(), 1);
2244                                 match events[0] {
2245                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2246                                                 assert!(update_add_htlcs.is_empty());
2247                                                 assert!(update_fail_htlcs.is_empty());
2248                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2249                                         },
2250                                         _ => panic!("Unexpected event"),
2251                                 };
2252                         }
2253                 }
2254         }
2255
2256         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2257         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2258         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2259         check_added_monitors!(nodes[2], 1);
2260         check_closed_broadcast!(nodes[2], true);
2261         let node2_commitment_txid;
2262         {
2263                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2264                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2265                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2266                 node2_commitment_txid = node_txn[0].txid();
2267
2268                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2269                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2270                 mine_transaction(&nodes[3], &node_txn[0]);
2271                 check_added_monitors!(nodes[3], 1);
2272                 check_preimage_claim(&nodes[3], &node_txn);
2273         }
2274         check_closed_broadcast!(nodes[3], true);
2275         assert_eq!(nodes[2].node.list_channels().len(), 0);
2276         assert_eq!(nodes[3].node.list_channels().len(), 1);
2277         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2278         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2279
2280         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2281         // confusing us in the following tests.
2282         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2283
2284         // One pending HTLC to time out:
2285         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2286         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2287         // buffer space).
2288
2289         let (close_chan_update_1, close_chan_update_2) = {
2290                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2291                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2292                 assert_eq!(events.len(), 2);
2293                 let close_chan_update_1 = match events[0] {
2294                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2295                                 msg.clone()
2296                         },
2297                         _ => panic!("Unexpected event"),
2298                 };
2299                 match events[1] {
2300                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2301                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2302                         },
2303                         _ => panic!("Unexpected event"),
2304                 }
2305                 check_added_monitors!(nodes[3], 1);
2306
2307                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2308                 {
2309                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2310                         node_txn.retain(|tx| {
2311                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2312                                         false
2313                                 } else { true }
2314                         });
2315                 }
2316
2317                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2318
2319                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2320                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2321
2322                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2323                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2324                 assert_eq!(events.len(), 2);
2325                 let close_chan_update_2 = match events[0] {
2326                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2327                                 msg.clone()
2328                         },
2329                         _ => panic!("Unexpected event"),
2330                 };
2331                 match events[1] {
2332                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2333                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2334                         },
2335                         _ => panic!("Unexpected event"),
2336                 }
2337                 check_added_monitors!(nodes[4], 1);
2338                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2339
2340                 mine_transaction(&nodes[4], &node_txn[0]);
2341                 check_preimage_claim(&nodes[4], &node_txn);
2342                 (close_chan_update_1, close_chan_update_2)
2343         };
2344         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2345         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2346         assert_eq!(nodes[3].node.list_channels().len(), 0);
2347         assert_eq!(nodes[4].node.list_channels().len(), 0);
2348
2349         assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2350                 ChannelMonitorUpdateStatus::Completed);
2351         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2352         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2353 }
2354
2355 #[test]
2356 fn test_justice_tx() {
2357         // Test justice txn built on revoked HTLC-Success tx, against both sides
2358         let mut alice_config = UserConfig::default();
2359         alice_config.channel_handshake_config.announced_channel = true;
2360         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2361         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2362         let mut bob_config = UserConfig::default();
2363         bob_config.channel_handshake_config.announced_channel = true;
2364         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2365         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2366         let user_cfgs = [Some(alice_config), Some(bob_config)];
2367         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2368         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2369         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2370         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2371         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2372         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2373         *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2374         // Create some new channels:
2375         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2376
2377         // A pending HTLC which will be revoked:
2378         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2379         // Get the will-be-revoked local txn from nodes[0]
2380         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2381         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2382         assert_eq!(revoked_local_txn[0].input.len(), 1);
2383         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2384         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2385         assert_eq!(revoked_local_txn[1].input.len(), 1);
2386         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2387         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2388         // Revoke the old state
2389         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2390
2391         {
2392                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2393                 {
2394                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2395                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2396                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2397
2398                         check_spends!(node_txn[0], revoked_local_txn[0]);
2399                         node_txn.swap_remove(0);
2400                 }
2401                 check_added_monitors!(nodes[1], 1);
2402                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2403                 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2404
2405                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2406                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2407                 // Verify broadcast of revoked HTLC-timeout
2408                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2409                 check_added_monitors!(nodes[0], 1);
2410                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2411                 // Broadcast revoked HTLC-timeout on node 1
2412                 mine_transaction(&nodes[1], &node_txn[1]);
2413                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2414         }
2415         get_announce_close_broadcast_events(&nodes, 0, 1);
2416
2417         assert_eq!(nodes[0].node.list_channels().len(), 0);
2418         assert_eq!(nodes[1].node.list_channels().len(), 0);
2419
2420         // We test justice_tx build by A on B's revoked HTLC-Success tx
2421         // Create some new channels:
2422         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2423         {
2424                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2425                 node_txn.clear();
2426         }
2427
2428         // A pending HTLC which will be revoked:
2429         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2430         // Get the will-be-revoked local txn from B
2431         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2432         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2433         assert_eq!(revoked_local_txn[0].input.len(), 1);
2434         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2435         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2436         // Revoke the old state
2437         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2438         {
2439                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2440                 {
2441                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2442                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2443                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2444
2445                         check_spends!(node_txn[0], revoked_local_txn[0]);
2446                         node_txn.swap_remove(0);
2447                 }
2448                 check_added_monitors!(nodes[0], 1);
2449                 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2450
2451                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2452                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2453                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2454                 check_added_monitors!(nodes[1], 1);
2455                 mine_transaction(&nodes[0], &node_txn[1]);
2456                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2457                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2458         }
2459         get_announce_close_broadcast_events(&nodes, 0, 1);
2460         assert_eq!(nodes[0].node.list_channels().len(), 0);
2461         assert_eq!(nodes[1].node.list_channels().len(), 0);
2462 }
2463
2464 #[test]
2465 fn revoked_output_claim() {
2466         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2467         // transaction is broadcast by its counterparty
2468         let chanmon_cfgs = create_chanmon_cfgs(2);
2469         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2470         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2471         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2472         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2473         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2474         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2475         assert_eq!(revoked_local_txn.len(), 1);
2476         // Only output is the full channel value back to nodes[0]:
2477         assert_eq!(revoked_local_txn[0].output.len(), 1);
2478         // Send a payment through, updating everyone's latest commitment txn
2479         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2480
2481         // Inform nodes[1] that nodes[0] broadcast a stale tx
2482         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2483         check_added_monitors!(nodes[1], 1);
2484         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2485         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2486         assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2487
2488         check_spends!(node_txn[0], revoked_local_txn[0]);
2489
2490         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2491         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2492         get_announce_close_broadcast_events(&nodes, 0, 1);
2493         check_added_monitors!(nodes[0], 1);
2494         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2495 }
2496
2497 #[test]
2498 fn claim_htlc_outputs_shared_tx() {
2499         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2500         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2501         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2502         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2503         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2504         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2505
2506         // Create some new channel:
2507         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2508
2509         // Rebalance the network to generate htlc in the two directions
2510         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2511         // 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
2512         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2513         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2514
2515         // Get the will-be-revoked local txn from node[0]
2516         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2517         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2518         assert_eq!(revoked_local_txn[0].input.len(), 1);
2519         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2520         assert_eq!(revoked_local_txn[1].input.len(), 1);
2521         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2522         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2523         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2524
2525         //Revoke the old state
2526         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2527
2528         {
2529                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2530                 check_added_monitors!(nodes[0], 1);
2531                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2532                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2533                 check_added_monitors!(nodes[1], 1);
2534                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2535                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2536                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2537
2538                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2539                 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2540
2541                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2542                 check_spends!(node_txn[0], revoked_local_txn[0]);
2543
2544                 let mut witness_lens = BTreeSet::new();
2545                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2546                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2547                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2548                 assert_eq!(witness_lens.len(), 3);
2549                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2550                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2551                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2552
2553                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2554                 // ANTI_REORG_DELAY confirmations.
2555                 mine_transaction(&nodes[1], &node_txn[0]);
2556                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2557                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2558         }
2559         get_announce_close_broadcast_events(&nodes, 0, 1);
2560         assert_eq!(nodes[0].node.list_channels().len(), 0);
2561         assert_eq!(nodes[1].node.list_channels().len(), 0);
2562 }
2563
2564 #[test]
2565 fn claim_htlc_outputs_single_tx() {
2566         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2567         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2568         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2569         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2570         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2571         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2572
2573         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2574
2575         // Rebalance the network to generate htlc in the two directions
2576         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2577         // 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
2578         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2579         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2580         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2581
2582         // Get the will-be-revoked local txn from node[0]
2583         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2584
2585         //Revoke the old state
2586         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2587
2588         {
2589                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2590                 check_added_monitors!(nodes[0], 1);
2591                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2592                 check_added_monitors!(nodes[1], 1);
2593                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2594                 let mut events = nodes[0].node.get_and_clear_pending_events();
2595                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2596                 match events.last().unwrap() {
2597                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2598                         _ => panic!("Unexpected event"),
2599                 }
2600
2601                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2602                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2603
2604                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2605                 assert_eq!(node_txn.len(), 7);
2606
2607                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2608                 assert_eq!(node_txn[0].input.len(), 1);
2609                 check_spends!(node_txn[0], chan_1.3);
2610                 assert_eq!(node_txn[1].input.len(), 1);
2611                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2612                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2613                 check_spends!(node_txn[1], node_txn[0]);
2614
2615                 // Justice transactions are indices 2-3-4
2616                 assert_eq!(node_txn[2].input.len(), 1);
2617                 assert_eq!(node_txn[3].input.len(), 1);
2618                 assert_eq!(node_txn[4].input.len(), 1);
2619
2620                 check_spends!(node_txn[2], revoked_local_txn[0]);
2621                 check_spends!(node_txn[3], revoked_local_txn[0]);
2622                 check_spends!(node_txn[4], revoked_local_txn[0]);
2623
2624                 let mut witness_lens = BTreeSet::new();
2625                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2626                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2627                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2628                 assert_eq!(witness_lens.len(), 3);
2629                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2630                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2631                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2632
2633                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2634                 // ANTI_REORG_DELAY confirmations.
2635                 mine_transaction(&nodes[1], &node_txn[2]);
2636                 mine_transaction(&nodes[1], &node_txn[3]);
2637                 mine_transaction(&nodes[1], &node_txn[4]);
2638                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2639                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2640         }
2641         get_announce_close_broadcast_events(&nodes, 0, 1);
2642         assert_eq!(nodes[0].node.list_channels().len(), 0);
2643         assert_eq!(nodes[1].node.list_channels().len(), 0);
2644 }
2645
2646 #[test]
2647 fn test_htlc_on_chain_success() {
2648         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2649         // the preimage backward accordingly. So here we test that ChannelManager is
2650         // broadcasting the right event to other nodes in payment path.
2651         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2652         // A --------------------> B ----------------------> C (preimage)
2653         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2654         // commitment transaction was broadcast.
2655         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2656         // towards B.
2657         // B should be able to claim via preimage if A then broadcasts its local tx.
2658         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2659         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2660         // PaymentSent event).
2661
2662         let chanmon_cfgs = create_chanmon_cfgs(3);
2663         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2664         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2665         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2666
2667         // Create some initial channels
2668         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2669         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2670
2671         // Ensure all nodes are at the same height
2672         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2673         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2674         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2675         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2676
2677         // Rebalance the network a bit by relaying one payment through all the channels...
2678         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2679         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2680
2681         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2682         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2683
2684         // Broadcast legit commitment tx from C on B's chain
2685         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2686         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2687         assert_eq!(commitment_tx.len(), 1);
2688         check_spends!(commitment_tx[0], chan_2.3);
2689         nodes[2].node.claim_funds(our_payment_preimage);
2690         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2691         nodes[2].node.claim_funds(our_payment_preimage_2);
2692         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2693         check_added_monitors!(nodes[2], 2);
2694         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2695         assert!(updates.update_add_htlcs.is_empty());
2696         assert!(updates.update_fail_htlcs.is_empty());
2697         assert!(updates.update_fail_malformed_htlcs.is_empty());
2698         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2699
2700         mine_transaction(&nodes[2], &commitment_tx[0]);
2701         check_closed_broadcast!(nodes[2], true);
2702         check_added_monitors!(nodes[2], 1);
2703         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2704         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2705         assert_eq!(node_txn.len(), 2);
2706         check_spends!(node_txn[0], commitment_tx[0]);
2707         check_spends!(node_txn[1], commitment_tx[0]);
2708         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2709         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2710         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2711         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2712         assert_eq!(node_txn[0].lock_time.0, 0);
2713         assert_eq!(node_txn[1].lock_time.0, 0);
2714
2715         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2716         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2717         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone(), node_txn[1].clone()]});
2718         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2719         {
2720                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2721                 assert_eq!(added_monitors.len(), 1);
2722                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2723                 added_monitors.clear();
2724         }
2725         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2726         assert_eq!(forwarded_events.len(), 3);
2727         match forwarded_events[0] {
2728                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2729                 _ => panic!("Unexpected event"),
2730         }
2731         let chan_id = Some(chan_1.2);
2732         match forwarded_events[1] {
2733                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2734                         assert_eq!(fee_earned_msat, Some(1000));
2735                         assert_eq!(prev_channel_id, chan_id);
2736                         assert_eq!(claim_from_onchain_tx, true);
2737                         assert_eq!(next_channel_id, Some(chan_2.2));
2738                 },
2739                 _ => panic!()
2740         }
2741         match forwarded_events[2] {
2742                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2743                         assert_eq!(fee_earned_msat, Some(1000));
2744                         assert_eq!(prev_channel_id, chan_id);
2745                         assert_eq!(claim_from_onchain_tx, true);
2746                         assert_eq!(next_channel_id, Some(chan_2.2));
2747                 },
2748                 _ => panic!()
2749         }
2750         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2751         {
2752                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2753                 assert_eq!(added_monitors.len(), 2);
2754                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2755                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2756                 added_monitors.clear();
2757         }
2758         assert_eq!(events.len(), 3);
2759
2760         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2761         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2762
2763         match nodes_2_event {
2764                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2765                 _ => panic!("Unexpected event"),
2766         }
2767
2768         match nodes_0_event {
2769                 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, .. } } => {
2770                         assert!(update_add_htlcs.is_empty());
2771                         assert!(update_fail_htlcs.is_empty());
2772                         assert_eq!(update_fulfill_htlcs.len(), 1);
2773                         assert!(update_fail_malformed_htlcs.is_empty());
2774                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2775                 },
2776                 _ => panic!("Unexpected event"),
2777         };
2778
2779         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2780         match events[0] {
2781                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2782                 _ => panic!("Unexpected event"),
2783         }
2784
2785         macro_rules! check_tx_local_broadcast {
2786                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2787                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2788                         assert_eq!(node_txn.len(), 2);
2789                         // Node[1]: 2 * HTLC-timeout tx
2790                         // Node[0]: 2 * HTLC-timeout tx
2791                         check_spends!(node_txn[0], $commitment_tx);
2792                         check_spends!(node_txn[1], $commitment_tx);
2793                         assert_ne!(node_txn[0].lock_time.0, 0);
2794                         assert_ne!(node_txn[1].lock_time.0, 0);
2795                         if $htlc_offered {
2796                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2797                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2798                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2799                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2800                         } else {
2801                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2802                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2803                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2804                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2805                         }
2806                         node_txn.clear();
2807                 } }
2808         }
2809         // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2810         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2811
2812         // Broadcast legit commitment tx from A on B's chain
2813         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2814         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2815         check_spends!(node_a_commitment_tx[0], chan_1.3);
2816         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2817         check_closed_broadcast!(nodes[1], true);
2818         check_added_monitors!(nodes[1], 1);
2819         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2820         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2821         assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2822         let commitment_spend =
2823                 if node_txn.len() == 1 {
2824                         &node_txn[0]
2825                 } else {
2826                         // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2827                         // FullBlockViaListen
2828                         if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2829                                 check_spends!(node_txn[1], commitment_tx[0]);
2830                                 check_spends!(node_txn[2], commitment_tx[0]);
2831                                 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2832                                 &node_txn[0]
2833                         } else {
2834                                 check_spends!(node_txn[0], commitment_tx[0]);
2835                                 check_spends!(node_txn[1], commitment_tx[0]);
2836                                 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2837                                 &node_txn[2]
2838                         }
2839                 };
2840
2841         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2842         assert_eq!(commitment_spend.input.len(), 2);
2843         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2844         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2845         assert_eq!(commitment_spend.lock_time.0, 0);
2846         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2847         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2848         // we already checked the same situation with A.
2849
2850         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2851         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2852         connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2853         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2854         check_closed_broadcast!(nodes[0], true);
2855         check_added_monitors!(nodes[0], 1);
2856         let events = nodes[0].node.get_and_clear_pending_events();
2857         assert_eq!(events.len(), 5);
2858         let mut first_claimed = false;
2859         for event in events {
2860                 match event {
2861                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2862                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2863                                         assert!(!first_claimed);
2864                                         first_claimed = true;
2865                                 } else {
2866                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2867                                         assert_eq!(payment_hash, payment_hash_2);
2868                                 }
2869                         },
2870                         Event::PaymentPathSuccessful { .. } => {},
2871                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2872                         _ => panic!("Unexpected event"),
2873                 }
2874         }
2875         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
2876 }
2877
2878 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2879         // Test that in case of a unilateral close onchain, we detect the state of output and
2880         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2881         // broadcasting the right event to other nodes in payment path.
2882         // A ------------------> B ----------------------> C (timeout)
2883         //    B's commitment tx                 C's commitment tx
2884         //            \                                  \
2885         //         B's HTLC timeout tx               B's timeout tx
2886
2887         let chanmon_cfgs = create_chanmon_cfgs(3);
2888         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2889         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2890         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2891         *nodes[0].connect_style.borrow_mut() = connect_style;
2892         *nodes[1].connect_style.borrow_mut() = connect_style;
2893         *nodes[2].connect_style.borrow_mut() = connect_style;
2894
2895         // Create some intial channels
2896         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2897         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2898
2899         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2900         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2901         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2902
2903         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2904
2905         // Broadcast legit commitment tx from C on B's chain
2906         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2907         check_spends!(commitment_tx[0], chan_2.3);
2908         nodes[2].node.fail_htlc_backwards(&payment_hash);
2909         check_added_monitors!(nodes[2], 0);
2910         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2911         check_added_monitors!(nodes[2], 1);
2912
2913         let events = nodes[2].node.get_and_clear_pending_msg_events();
2914         assert_eq!(events.len(), 1);
2915         match events[0] {
2916                 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, .. } } => {
2917                         assert!(update_add_htlcs.is_empty());
2918                         assert!(!update_fail_htlcs.is_empty());
2919                         assert!(update_fulfill_htlcs.is_empty());
2920                         assert!(update_fail_malformed_htlcs.is_empty());
2921                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2922                 },
2923                 _ => panic!("Unexpected event"),
2924         };
2925         mine_transaction(&nodes[2], &commitment_tx[0]);
2926         check_closed_broadcast!(nodes[2], true);
2927         check_added_monitors!(nodes[2], 1);
2928         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2929         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2930         assert_eq!(node_txn.len(), 0);
2931
2932         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2933         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2934         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2935         mine_transaction(&nodes[1], &commitment_tx[0]);
2936         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2937         let timeout_tx;
2938         {
2939                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2940                 assert_eq!(node_txn.len(), 3); // 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2941
2942                 check_spends!(node_txn[2], commitment_tx[0]);
2943                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2944
2945                 check_spends!(node_txn[0], chan_2.3);
2946                 check_spends!(node_txn[1], node_txn[0]);
2947                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2948                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2949
2950                 timeout_tx = node_txn[2].clone();
2951                 node_txn.clear();
2952         }
2953
2954         mine_transaction(&nodes[1], &timeout_tx);
2955         check_added_monitors!(nodes[1], 1);
2956         check_closed_broadcast!(nodes[1], true);
2957
2958         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2959
2960         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 }]);
2961         check_added_monitors!(nodes[1], 1);
2962         let events = nodes[1].node.get_and_clear_pending_msg_events();
2963         assert_eq!(events.len(), 1);
2964         match events[0] {
2965                 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, .. } } => {
2966                         assert!(update_add_htlcs.is_empty());
2967                         assert!(!update_fail_htlcs.is_empty());
2968                         assert!(update_fulfill_htlcs.is_empty());
2969                         assert!(update_fail_malformed_htlcs.is_empty());
2970                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2971                 },
2972                 _ => panic!("Unexpected event"),
2973         };
2974
2975         // Broadcast legit commitment tx from B on A's chain
2976         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2977         check_spends!(commitment_tx[0], chan_1.3);
2978
2979         mine_transaction(&nodes[0], &commitment_tx[0]);
2980         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2981
2982         check_closed_broadcast!(nodes[0], true);
2983         check_added_monitors!(nodes[0], 1);
2984         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2985         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
2986         assert_eq!(node_txn.len(), 1);
2987         check_spends!(node_txn[0], commitment_tx[0]);
2988         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2989 }
2990
2991 #[test]
2992 fn test_htlc_on_chain_timeout() {
2993         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
2994         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
2995         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
2996 }
2997
2998 #[test]
2999 fn test_simple_commitment_revoked_fail_backward() {
3000         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3001         // and fail backward accordingly.
3002
3003         let chanmon_cfgs = create_chanmon_cfgs(3);
3004         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3005         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3006         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3007
3008         // Create some initial channels
3009         create_announced_chan_between_nodes(&nodes, 0, 1);
3010         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3011
3012         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3013         // Get the will-be-revoked local txn from nodes[2]
3014         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3015         // Revoke the old state
3016         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3017
3018         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3019
3020         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3021         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3022         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3023         check_added_monitors!(nodes[1], 1);
3024         check_closed_broadcast!(nodes[1], true);
3025
3026         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 }]);
3027         check_added_monitors!(nodes[1], 1);
3028         let events = nodes[1].node.get_and_clear_pending_msg_events();
3029         assert_eq!(events.len(), 1);
3030         match events[0] {
3031                 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, .. } } => {
3032                         assert!(update_add_htlcs.is_empty());
3033                         assert_eq!(update_fail_htlcs.len(), 1);
3034                         assert!(update_fulfill_htlcs.is_empty());
3035                         assert!(update_fail_malformed_htlcs.is_empty());
3036                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3037
3038                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3039                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3040                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3041                 },
3042                 _ => panic!("Unexpected event"),
3043         }
3044 }
3045
3046 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3047         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3048         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3049         // commitment transaction anymore.
3050         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3051         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3052         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3053         // technically disallowed and we should probably handle it reasonably.
3054         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3055         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3056         // transactions:
3057         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3058         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3059         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3060         //   and once they revoke the previous commitment transaction (allowing us to send a new
3061         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3062         let chanmon_cfgs = create_chanmon_cfgs(3);
3063         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3064         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3065         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3066
3067         // Create some initial channels
3068         create_announced_chan_between_nodes(&nodes, 0, 1);
3069         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3070
3071         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 });
3072         // Get the will-be-revoked local txn from nodes[2]
3073         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3074         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3075         // Revoke the old state
3076         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3077
3078         let value = if use_dust {
3079                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3080                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3081                 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3082                         .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3083         } else { 3000000 };
3084
3085         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3086         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3087         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3088
3089         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3090         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3091         check_added_monitors!(nodes[2], 1);
3092         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3093         assert!(updates.update_add_htlcs.is_empty());
3094         assert!(updates.update_fulfill_htlcs.is_empty());
3095         assert!(updates.update_fail_malformed_htlcs.is_empty());
3096         assert_eq!(updates.update_fail_htlcs.len(), 1);
3097         assert!(updates.update_fee.is_none());
3098         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3099         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3100         // Drop the last RAA from 3 -> 2
3101
3102         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3103         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3104         check_added_monitors!(nodes[2], 1);
3105         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3106         assert!(updates.update_add_htlcs.is_empty());
3107         assert!(updates.update_fulfill_htlcs.is_empty());
3108         assert!(updates.update_fail_malformed_htlcs.is_empty());
3109         assert_eq!(updates.update_fail_htlcs.len(), 1);
3110         assert!(updates.update_fee.is_none());
3111         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3112         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3113         check_added_monitors!(nodes[1], 1);
3114         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3115         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3116         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3117         check_added_monitors!(nodes[2], 1);
3118
3119         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3120         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3121         check_added_monitors!(nodes[2], 1);
3122         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3123         assert!(updates.update_add_htlcs.is_empty());
3124         assert!(updates.update_fulfill_htlcs.is_empty());
3125         assert!(updates.update_fail_malformed_htlcs.is_empty());
3126         assert_eq!(updates.update_fail_htlcs.len(), 1);
3127         assert!(updates.update_fee.is_none());
3128         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3129         // At this point first_payment_hash has dropped out of the latest two commitment
3130         // transactions that nodes[1] is tracking...
3131         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3132         check_added_monitors!(nodes[1], 1);
3133         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3134         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3135         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3136         check_added_monitors!(nodes[2], 1);
3137
3138         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3139         // on nodes[2]'s RAA.
3140         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3141         nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3142         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3143         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3144         check_added_monitors!(nodes[1], 0);
3145
3146         if deliver_bs_raa {
3147                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3148                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3149                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3150                 check_added_monitors!(nodes[1], 1);
3151                 let events = nodes[1].node.get_and_clear_pending_events();
3152                 assert_eq!(events.len(), 2);
3153                 match events[0] {
3154                         Event::PendingHTLCsForwardable { .. } => { },
3155                         _ => panic!("Unexpected event"),
3156                 };
3157                 match events[1] {
3158                         Event::HTLCHandlingFailed { .. } => { },
3159                         _ => panic!("Unexpected event"),
3160                 }
3161                 // Deliberately don't process the pending fail-back so they all fail back at once after
3162                 // block connection just like the !deliver_bs_raa case
3163         }
3164
3165         let mut failed_htlcs = HashSet::new();
3166         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3167
3168         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3169         check_added_monitors!(nodes[1], 1);
3170         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3171
3172         let events = nodes[1].node.get_and_clear_pending_events();
3173         assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3174         match events[0] {
3175                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3176                 _ => panic!("Unexepected event"),
3177         }
3178         match events[1] {
3179                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3180                         assert_eq!(*payment_hash, fourth_payment_hash);
3181                 },
3182                 _ => panic!("Unexpected event"),
3183         }
3184         match events[2] {
3185                 Event::PaymentFailed { ref payment_hash, .. } => {
3186                         assert_eq!(*payment_hash, fourth_payment_hash);
3187                 },
3188                 _ => panic!("Unexpected event"),
3189         }
3190
3191         nodes[1].node.process_pending_htlc_forwards();
3192         check_added_monitors!(nodes[1], 1);
3193
3194         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3195         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3196
3197         if deliver_bs_raa {
3198                 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3199                 match nodes_2_event {
3200                         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, .. } } => {
3201                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3202                                 assert_eq!(update_add_htlcs.len(), 1);
3203                                 assert!(update_fulfill_htlcs.is_empty());
3204                                 assert!(update_fail_htlcs.is_empty());
3205                                 assert!(update_fail_malformed_htlcs.is_empty());
3206                         },
3207                         _ => panic!("Unexpected event"),
3208                 }
3209         }
3210
3211         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3212         match nodes_2_event {
3213                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3214                         assert_eq!(channel_id, chan_2.2);
3215                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3216                 },
3217                 _ => panic!("Unexpected event"),
3218         }
3219
3220         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3221         match nodes_0_event {
3222                 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, .. } } => {
3223                         assert!(update_add_htlcs.is_empty());
3224                         assert_eq!(update_fail_htlcs.len(), 3);
3225                         assert!(update_fulfill_htlcs.is_empty());
3226                         assert!(update_fail_malformed_htlcs.is_empty());
3227                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3228
3229                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3230                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3231                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3232
3233                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3234
3235                         let events = nodes[0].node.get_and_clear_pending_events();
3236                         assert_eq!(events.len(), 6);
3237                         match events[0] {
3238                                 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3239                                         assert!(failed_htlcs.insert(payment_hash.0));
3240                                         // If we delivered B's RAA we got an unknown preimage error, not something
3241                                         // that we should update our routing table for.
3242                                         if !deliver_bs_raa {
3243                                                 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3244                                         }
3245                                 },
3246                                 _ => panic!("Unexpected event"),
3247                         }
3248                         match events[1] {
3249                                 Event::PaymentFailed { ref payment_hash, .. } => {
3250                                         assert_eq!(*payment_hash, first_payment_hash);
3251                                 },
3252                                 _ => panic!("Unexpected event"),
3253                         }
3254                         match events[2] {
3255                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3256                                         assert!(failed_htlcs.insert(payment_hash.0));
3257                                 },
3258                                 _ => panic!("Unexpected event"),
3259                         }
3260                         match events[3] {
3261                                 Event::PaymentFailed { ref payment_hash, .. } => {
3262                                         assert_eq!(*payment_hash, second_payment_hash);
3263                                 },
3264                                 _ => panic!("Unexpected event"),
3265                         }
3266                         match events[4] {
3267                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3268                                         assert!(failed_htlcs.insert(payment_hash.0));
3269                                 },
3270                                 _ => panic!("Unexpected event"),
3271                         }
3272                         match events[5] {
3273                                 Event::PaymentFailed { ref payment_hash, .. } => {
3274                                         assert_eq!(*payment_hash, third_payment_hash);
3275                                 },
3276                                 _ => panic!("Unexpected event"),
3277                         }
3278                 },
3279                 _ => panic!("Unexpected event"),
3280         }
3281
3282         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3283         match events[0] {
3284                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3285                 _ => panic!("Unexpected event"),
3286         }
3287
3288         assert!(failed_htlcs.contains(&first_payment_hash.0));
3289         assert!(failed_htlcs.contains(&second_payment_hash.0));
3290         assert!(failed_htlcs.contains(&third_payment_hash.0));
3291 }
3292
3293 #[test]
3294 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3295         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3296         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3297         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3298         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3299 }
3300
3301 #[test]
3302 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3303         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3304         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3305         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3306         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3307 }
3308
3309 #[test]
3310 fn fail_backward_pending_htlc_upon_channel_failure() {
3311         let chanmon_cfgs = create_chanmon_cfgs(2);
3312         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3313         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3314         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3315         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3316
3317         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3318         {
3319                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3320                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
3321                 check_added_monitors!(nodes[0], 1);
3322
3323                 let payment_event = {
3324                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3325                         assert_eq!(events.len(), 1);
3326                         SendEvent::from_event(events.remove(0))
3327                 };
3328                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3329                 assert_eq!(payment_event.msgs.len(), 1);
3330         }
3331
3332         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3333         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3334         {
3335                 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3336                 check_added_monitors!(nodes[0], 0);
3337
3338                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3339         }
3340
3341         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3342         {
3343                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3344
3345                 let secp_ctx = Secp256k1::new();
3346                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3347                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3348                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3349                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3350                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3351
3352                 // Send a 0-msat update_add_htlc to fail the channel.
3353                 let update_add_htlc = msgs::UpdateAddHTLC {
3354                         channel_id: chan.2,
3355                         htlc_id: 0,
3356                         amount_msat: 0,
3357                         payment_hash,
3358                         cltv_expiry,
3359                         onion_routing_packet,
3360                 };
3361                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3362         }
3363         let events = nodes[0].node.get_and_clear_pending_events();
3364         assert_eq!(events.len(), 3);
3365         // Check that Alice fails backward the pending HTLC from the second payment.
3366         match events[0] {
3367                 Event::PaymentPathFailed { payment_hash, .. } => {
3368                         assert_eq!(payment_hash, failed_payment_hash);
3369                 },
3370                 _ => panic!("Unexpected event"),
3371         }
3372         match events[1] {
3373                 Event::PaymentFailed { payment_hash, .. } => {
3374                         assert_eq!(payment_hash, failed_payment_hash);
3375                 },
3376                 _ => panic!("Unexpected event"),
3377         }
3378         match events[2] {
3379                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3380                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3381                 },
3382                 _ => panic!("Unexpected event {:?}", events[1]),
3383         }
3384         check_closed_broadcast!(nodes[0], true);
3385         check_added_monitors!(nodes[0], 1);
3386 }
3387
3388 #[test]
3389 fn test_htlc_ignore_latest_remote_commitment() {
3390         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3391         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3392         let chanmon_cfgs = create_chanmon_cfgs(2);
3393         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3394         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3395         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3396         if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3397                 // We rely on the ability to connect a block redundantly, which isn't allowed via
3398                 // `chain::Listen`, so we never run the test if we randomly get assigned that
3399                 // connect_style.
3400                 return;
3401         }
3402         create_announced_chan_between_nodes(&nodes, 0, 1);
3403
3404         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3405         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3406         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3407         check_closed_broadcast!(nodes[0], true);
3408         check_added_monitors!(nodes[0], 1);
3409         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3410
3411         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3412         assert_eq!(node_txn.len(), 3);
3413         assert_eq!(node_txn[0], node_txn[1]);
3414
3415         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
3416         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3417         check_closed_broadcast!(nodes[1], true);
3418         check_added_monitors!(nodes[1], 1);
3419         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3420
3421         // Duplicate the connect_block call since this may happen due to other listeners
3422         // registering new transactions
3423         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3424 }
3425
3426 #[test]
3427 fn test_force_close_fail_back() {
3428         // Check which HTLCs are failed-backwards on channel force-closure
3429         let chanmon_cfgs = create_chanmon_cfgs(3);
3430         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3431         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3432         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3433         create_announced_chan_between_nodes(&nodes, 0, 1);
3434         create_announced_chan_between_nodes(&nodes, 1, 2);
3435
3436         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3437
3438         let mut payment_event = {
3439                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3440                 check_added_monitors!(nodes[0], 1);
3441
3442                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3443                 assert_eq!(events.len(), 1);
3444                 SendEvent::from_event(events.remove(0))
3445         };
3446
3447         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3448         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3449
3450         expect_pending_htlcs_forwardable!(nodes[1]);
3451
3452         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3453         assert_eq!(events_2.len(), 1);
3454         payment_event = SendEvent::from_event(events_2.remove(0));
3455         assert_eq!(payment_event.msgs.len(), 1);
3456
3457         check_added_monitors!(nodes[1], 1);
3458         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3459         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3460         check_added_monitors!(nodes[2], 1);
3461         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3462
3463         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3464         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3465         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3466
3467         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3468         check_closed_broadcast!(nodes[2], true);
3469         check_added_monitors!(nodes[2], 1);
3470         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3471         let tx = {
3472                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3473                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3474                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3475                 // back to nodes[1] upon timeout otherwise.
3476                 assert_eq!(node_txn.len(), 1);
3477                 node_txn.remove(0)
3478         };
3479
3480         mine_transaction(&nodes[1], &tx);
3481
3482         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3483         check_closed_broadcast!(nodes[1], true);
3484         check_added_monitors!(nodes[1], 1);
3485         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3486
3487         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3488         {
3489                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3490                         .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);
3491         }
3492         mine_transaction(&nodes[2], &tx);
3493         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3494         assert_eq!(node_txn.len(), 1);
3495         assert_eq!(node_txn[0].input.len(), 1);
3496         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3497         assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3498         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3499
3500         check_spends!(node_txn[0], tx);
3501 }
3502
3503 #[test]
3504 fn test_dup_events_on_peer_disconnect() {
3505         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3506         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3507         // as we used to generate the event immediately upon receipt of the payment preimage in the
3508         // update_fulfill_htlc message.
3509
3510         let chanmon_cfgs = create_chanmon_cfgs(2);
3511         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3512         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3513         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3514         create_announced_chan_between_nodes(&nodes, 0, 1);
3515
3516         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3517
3518         nodes[1].node.claim_funds(payment_preimage);
3519         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3520         check_added_monitors!(nodes[1], 1);
3521         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3522         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3523         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3524
3525         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3526         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3527
3528         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3529         expect_payment_path_successful!(nodes[0]);
3530 }
3531
3532 #[test]
3533 fn test_peer_disconnected_before_funding_broadcasted() {
3534         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3535         // before the funding transaction has been broadcasted.
3536         let chanmon_cfgs = create_chanmon_cfgs(2);
3537         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3538         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3539         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3540
3541         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3542         // broadcasted, even though it's created by `nodes[0]`.
3543         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();
3544         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3545         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3546         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3547         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3548
3549         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3550         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3551
3552         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3553
3554         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3555         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3556
3557         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3558         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3559         // broadcasted.
3560         {
3561                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3562         }
3563
3564         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3565         // disconnected before the funding transaction was broadcasted.
3566         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3567         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3568
3569         check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3570         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3571 }
3572
3573 #[test]
3574 fn test_simple_peer_disconnect() {
3575         // Test that we can reconnect when there are no lost messages
3576         let chanmon_cfgs = create_chanmon_cfgs(3);
3577         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3578         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3579         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3580         create_announced_chan_between_nodes(&nodes, 0, 1);
3581         create_announced_chan_between_nodes(&nodes, 1, 2);
3582
3583         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3584         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3585         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3586
3587         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3588         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3589         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3590         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3591
3592         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3593         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3594         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3595
3596         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3597         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3598         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3599         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3600
3601         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3602         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3603
3604         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3605         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3606
3607         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3608         {
3609                 let events = nodes[0].node.get_and_clear_pending_events();
3610                 assert_eq!(events.len(), 4);
3611                 match events[0] {
3612                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3613                                 assert_eq!(payment_preimage, payment_preimage_3);
3614                                 assert_eq!(payment_hash, payment_hash_3);
3615                         },
3616                         _ => panic!("Unexpected event"),
3617                 }
3618                 match events[1] {
3619                         Event::PaymentPathSuccessful { .. } => {},
3620                         _ => panic!("Unexpected event"),
3621                 }
3622                 match events[2] {
3623                         Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3624                                 assert_eq!(payment_hash, payment_hash_5);
3625                                 assert!(payment_failed_permanently);
3626                         },
3627                         _ => panic!("Unexpected event"),
3628                 }
3629                 match events[3] {
3630                         Event::PaymentFailed { payment_hash, .. } => {
3631                                 assert_eq!(payment_hash, payment_hash_5);
3632                         },
3633                         _ => panic!("Unexpected event"),
3634                 }
3635         }
3636
3637         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3638         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3639 }
3640
3641 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3642         // Test that we can reconnect when in-flight HTLC updates get dropped
3643         let chanmon_cfgs = create_chanmon_cfgs(2);
3644         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3645         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3646         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3647
3648         let mut as_channel_ready = None;
3649         let channel_id = if messages_delivered == 0 {
3650                 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3651                 as_channel_ready = Some(channel_ready);
3652                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3653                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3654                 // it before the channel_reestablish message.
3655                 chan_id
3656         } else {
3657                 create_announced_chan_between_nodes(&nodes, 0, 1).2
3658         };
3659
3660         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3661
3662         let payment_event = {
3663                 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3664                 check_added_monitors!(nodes[0], 1);
3665
3666                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3667                 assert_eq!(events.len(), 1);
3668                 SendEvent::from_event(events.remove(0))
3669         };
3670         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3671
3672         if messages_delivered < 2 {
3673                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3674         } else {
3675                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3676                 if messages_delivered >= 3 {
3677                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3678                         check_added_monitors!(nodes[1], 1);
3679                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3680
3681                         if messages_delivered >= 4 {
3682                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3683                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3684                                 check_added_monitors!(nodes[0], 1);
3685
3686                                 if messages_delivered >= 5 {
3687                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3688                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3689                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3690                                         check_added_monitors!(nodes[0], 1);
3691
3692                                         if messages_delivered >= 6 {
3693                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3694                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3695                                                 check_added_monitors!(nodes[1], 1);
3696                                         }
3697                                 }
3698                         }
3699                 }
3700         }
3701
3702         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3703         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3704         if messages_delivered < 3 {
3705                 if simulate_broken_lnd {
3706                         // lnd has a long-standing bug where they send a channel_ready prior to a
3707                         // channel_reestablish if you reconnect prior to channel_ready time.
3708                         //
3709                         // Here we simulate that behavior, delivering a channel_ready immediately on
3710                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3711                         // in `reconnect_nodes` but we currently don't fail based on that.
3712                         //
3713                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3714                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3715                 }
3716                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3717                 // received on either side, both sides will need to resend them.
3718                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3719         } else if messages_delivered == 3 {
3720                 // nodes[0] still wants its RAA + commitment_signed
3721                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3722         } else if messages_delivered == 4 {
3723                 // nodes[0] still wants its commitment_signed
3724                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3725         } else if messages_delivered == 5 {
3726                 // nodes[1] still wants its final RAA
3727                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3728         } else if messages_delivered == 6 {
3729                 // Everything was delivered...
3730                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3731         }
3732
3733         let events_1 = nodes[1].node.get_and_clear_pending_events();
3734         if messages_delivered == 0 {
3735                 assert_eq!(events_1.len(), 2);
3736                 match events_1[0] {
3737                         Event::ChannelReady { .. } => { },
3738                         _ => panic!("Unexpected event"),
3739                 };
3740                 match events_1[1] {
3741                         Event::PendingHTLCsForwardable { .. } => { },
3742                         _ => panic!("Unexpected event"),
3743                 };
3744         } else {
3745                 assert_eq!(events_1.len(), 1);
3746                 match events_1[0] {
3747                         Event::PendingHTLCsForwardable { .. } => { },
3748                         _ => panic!("Unexpected event"),
3749                 };
3750         }
3751
3752         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3753         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3754         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3755
3756         nodes[1].node.process_pending_htlc_forwards();
3757
3758         let events_2 = nodes[1].node.get_and_clear_pending_events();
3759         assert_eq!(events_2.len(), 1);
3760         match events_2[0] {
3761                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
3762                         assert_eq!(payment_hash_1, *payment_hash);
3763                         assert_eq!(amount_msat, 1_000_000);
3764                         assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3765                         assert_eq!(via_channel_id, Some(channel_id));
3766                         match &purpose {
3767                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3768                                         assert!(payment_preimage.is_none());
3769                                         assert_eq!(payment_secret_1, *payment_secret);
3770                                 },
3771                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3772                         }
3773                 },
3774                 _ => panic!("Unexpected event"),
3775         }
3776
3777         nodes[1].node.claim_funds(payment_preimage_1);
3778         check_added_monitors!(nodes[1], 1);
3779         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3780
3781         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3782         assert_eq!(events_3.len(), 1);
3783         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3784                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3785                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3786                         assert!(updates.update_add_htlcs.is_empty());
3787                         assert!(updates.update_fail_htlcs.is_empty());
3788                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3789                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3790                         assert!(updates.update_fee.is_none());
3791                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3792                 },
3793                 _ => panic!("Unexpected event"),
3794         };
3795
3796         if messages_delivered >= 1 {
3797                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3798
3799                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3800                 assert_eq!(events_4.len(), 1);
3801                 match events_4[0] {
3802                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3803                                 assert_eq!(payment_preimage_1, *payment_preimage);
3804                                 assert_eq!(payment_hash_1, *payment_hash);
3805                         },
3806                         _ => panic!("Unexpected event"),
3807                 }
3808
3809                 if messages_delivered >= 2 {
3810                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3811                         check_added_monitors!(nodes[0], 1);
3812                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3813
3814                         if messages_delivered >= 3 {
3815                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3816                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3817                                 check_added_monitors!(nodes[1], 1);
3818
3819                                 if messages_delivered >= 4 {
3820                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3821                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3822                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3823                                         check_added_monitors!(nodes[1], 1);
3824
3825                                         if messages_delivered >= 5 {
3826                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3827                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3828                                                 check_added_monitors!(nodes[0], 1);
3829                                         }
3830                                 }
3831                         }
3832                 }
3833         }
3834
3835         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3836         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3837         if messages_delivered < 2 {
3838                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3839                 if messages_delivered < 1 {
3840                         expect_payment_sent!(nodes[0], payment_preimage_1);
3841                 } else {
3842                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3843                 }
3844         } else if messages_delivered == 2 {
3845                 // nodes[0] still wants its RAA + commitment_signed
3846                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3847         } else if messages_delivered == 3 {
3848                 // nodes[0] still wants its commitment_signed
3849                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3850         } else if messages_delivered == 4 {
3851                 // nodes[1] still wants its final RAA
3852                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3853         } else if messages_delivered == 5 {
3854                 // Everything was delivered...
3855                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3856         }
3857
3858         if messages_delivered == 1 || messages_delivered == 2 {
3859                 expect_payment_path_successful!(nodes[0]);
3860         }
3861         if messages_delivered <= 5 {
3862                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3863                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3864         }
3865         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3866
3867         if messages_delivered > 2 {
3868                 expect_payment_path_successful!(nodes[0]);
3869         }
3870
3871         // Channel should still work fine...
3872         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3873         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3874         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3875 }
3876
3877 #[test]
3878 fn test_drop_messages_peer_disconnect_a() {
3879         do_test_drop_messages_peer_disconnect(0, true);
3880         do_test_drop_messages_peer_disconnect(0, false);
3881         do_test_drop_messages_peer_disconnect(1, false);
3882         do_test_drop_messages_peer_disconnect(2, false);
3883 }
3884
3885 #[test]
3886 fn test_drop_messages_peer_disconnect_b() {
3887         do_test_drop_messages_peer_disconnect(3, false);
3888         do_test_drop_messages_peer_disconnect(4, false);
3889         do_test_drop_messages_peer_disconnect(5, false);
3890         do_test_drop_messages_peer_disconnect(6, false);
3891 }
3892
3893 #[test]
3894 fn test_channel_ready_without_best_block_updated() {
3895         // Previously, if we were offline when a funding transaction was locked in, and then we came
3896         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3897         // generate a channel_ready until a later best_block_updated. This tests that we generate the
3898         // channel_ready immediately instead.
3899         let chanmon_cfgs = create_chanmon_cfgs(2);
3900         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3901         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3902         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3903         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3904
3905         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
3906
3907         let conf_height = nodes[0].best_block_info().1 + 1;
3908         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3909         let block_txn = [funding_tx];
3910         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3911         let conf_block_header = nodes[0].get_block_header(conf_height);
3912         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3913
3914         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
3915         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
3916         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3917 }
3918
3919 #[test]
3920 fn test_drop_messages_peer_disconnect_dual_htlc() {
3921         // Test that we can handle reconnecting when both sides of a channel have pending
3922         // commitment_updates when we disconnect.
3923         let chanmon_cfgs = create_chanmon_cfgs(2);
3924         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3925         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3926         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3927         create_announced_chan_between_nodes(&nodes, 0, 1);
3928
3929         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3930
3931         // Now try to send a second payment which will fail to send
3932         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3933         nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
3934         check_added_monitors!(nodes[0], 1);
3935
3936         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3937         assert_eq!(events_1.len(), 1);
3938         match events_1[0] {
3939                 MessageSendEvent::UpdateHTLCs { .. } => {},
3940                 _ => panic!("Unexpected event"),
3941         }
3942
3943         nodes[1].node.claim_funds(payment_preimage_1);
3944         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3945         check_added_monitors!(nodes[1], 1);
3946
3947         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3948         assert_eq!(events_2.len(), 1);
3949         match events_2[0] {
3950                 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 } } => {
3951                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3952                         assert!(update_add_htlcs.is_empty());
3953                         assert_eq!(update_fulfill_htlcs.len(), 1);
3954                         assert!(update_fail_htlcs.is_empty());
3955                         assert!(update_fail_malformed_htlcs.is_empty());
3956                         assert!(update_fee.is_none());
3957
3958                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3959                         let events_3 = nodes[0].node.get_and_clear_pending_events();
3960                         assert_eq!(events_3.len(), 1);
3961                         match events_3[0] {
3962                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3963                                         assert_eq!(*payment_preimage, payment_preimage_1);
3964                                         assert_eq!(*payment_hash, payment_hash_1);
3965                                 },
3966                                 _ => panic!("Unexpected event"),
3967                         }
3968
3969                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3970                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3971                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3972                         check_added_monitors!(nodes[0], 1);
3973                 },
3974                 _ => panic!("Unexpected event"),
3975         }
3976
3977         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3978         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3979
3980         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();
3981         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3982         assert_eq!(reestablish_1.len(), 1);
3983         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();
3984         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3985         assert_eq!(reestablish_2.len(), 1);
3986
3987         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3988         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3989         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3990         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3991
3992         assert!(as_resp.0.is_none());
3993         assert!(bs_resp.0.is_none());
3994
3995         assert!(bs_resp.1.is_none());
3996         assert!(bs_resp.2.is_none());
3997
3998         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3999
4000         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4001         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4002         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4003         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4004         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4005         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4006         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4007         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4008         // No commitment_signed so get_event_msg's assert(len == 1) passes
4009         check_added_monitors!(nodes[1], 1);
4010
4011         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4012         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4013         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4014         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4015         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4016         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4017         assert!(bs_second_commitment_signed.update_fee.is_none());
4018         check_added_monitors!(nodes[1], 1);
4019
4020         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4021         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4022         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4023         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4024         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4025         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4026         assert!(as_commitment_signed.update_fee.is_none());
4027         check_added_monitors!(nodes[0], 1);
4028
4029         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4030         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4031         // No commitment_signed so get_event_msg's assert(len == 1) passes
4032         check_added_monitors!(nodes[0], 1);
4033
4034         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4035         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4036         // No commitment_signed so get_event_msg's assert(len == 1) passes
4037         check_added_monitors!(nodes[1], 1);
4038
4039         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4040         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4041         check_added_monitors!(nodes[1], 1);
4042
4043         expect_pending_htlcs_forwardable!(nodes[1]);
4044
4045         let events_5 = nodes[1].node.get_and_clear_pending_events();
4046         assert_eq!(events_5.len(), 1);
4047         match events_5[0] {
4048                 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4049                         assert_eq!(payment_hash_2, *payment_hash);
4050                         match &purpose {
4051                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4052                                         assert!(payment_preimage.is_none());
4053                                         assert_eq!(payment_secret_2, *payment_secret);
4054                                 },
4055                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4056                         }
4057                 },
4058                 _ => panic!("Unexpected event"),
4059         }
4060
4061         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4062         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4063         check_added_monitors!(nodes[0], 1);
4064
4065         expect_payment_path_successful!(nodes[0]);
4066         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4067 }
4068
4069 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4070         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4071         // to avoid our counterparty failing the channel.
4072         let chanmon_cfgs = create_chanmon_cfgs(2);
4073         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4074         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4075         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4076
4077         create_announced_chan_between_nodes(&nodes, 0, 1);
4078
4079         let our_payment_hash = if send_partial_mpp {
4080                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4081                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4082                 // indicates there are more HTLCs coming.
4083                 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.
4084                 let payment_id = PaymentId([42; 32]);
4085                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(payment_secret), payment_id, &route).unwrap();
4086                 nodes[0].node.test_send_payment_along_path(&route.paths[0], &route.payment_params, &our_payment_hash, &Some(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[0]).unwrap();
4087                 check_added_monitors!(nodes[0], 1);
4088                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4089                 assert_eq!(events.len(), 1);
4090                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4091                 // hop should *not* yet generate any PaymentClaimable event(s).
4092                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4093                 our_payment_hash
4094         } else {
4095                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4096         };
4097
4098         let mut block = Block {
4099                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
4100                 txdata: vec![],
4101         };
4102         connect_block(&nodes[0], &block);
4103         connect_block(&nodes[1], &block);
4104         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4105         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4106                 block.header.prev_blockhash = block.block_hash();
4107                 connect_block(&nodes[0], &block);
4108                 connect_block(&nodes[1], &block);
4109         }
4110
4111         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4112
4113         check_added_monitors!(nodes[1], 1);
4114         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4115         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4116         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4117         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4118         assert!(htlc_timeout_updates.update_fee.is_none());
4119
4120         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4121         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4122         // 100_000 msat as u64, followed by the height at which we failed back above
4123         let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4124         expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4125         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4126 }
4127
4128 #[test]
4129 fn test_htlc_timeout() {
4130         do_test_htlc_timeout(true);
4131         do_test_htlc_timeout(false);
4132 }
4133
4134 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4135         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4136         let chanmon_cfgs = create_chanmon_cfgs(3);
4137         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4138         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4139         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4140         create_announced_chan_between_nodes(&nodes, 0, 1);
4141         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4142
4143         // Make sure all nodes are at the same starting height
4144         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4145         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4146         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4147
4148         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4149         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4150         {
4151                 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4152         }
4153         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4154         check_added_monitors!(nodes[1], 1);
4155
4156         // Now attempt to route a second payment, which should be placed in the holding cell
4157         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4158         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4159         sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4160         if forwarded_htlc {
4161                 check_added_monitors!(nodes[0], 1);
4162                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4163                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4164                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4165                 expect_pending_htlcs_forwardable!(nodes[1]);
4166         }
4167         check_added_monitors!(nodes[1], 0);
4168
4169         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4170         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4171         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4172         connect_blocks(&nodes[1], 1);
4173
4174         if forwarded_htlc {
4175                 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 }]);
4176                 check_added_monitors!(nodes[1], 1);
4177                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4178                 assert_eq!(fail_commit.len(), 1);
4179                 match fail_commit[0] {
4180                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4181                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4182                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4183                         },
4184                         _ => unreachable!(),
4185                 }
4186                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4187         } else {
4188                 expect_payment_failed!(nodes[1], second_payment_hash, false);
4189         }
4190 }
4191
4192 #[test]
4193 fn test_holding_cell_htlc_add_timeouts() {
4194         do_test_holding_cell_htlc_add_timeouts(false);
4195         do_test_holding_cell_htlc_add_timeouts(true);
4196 }
4197
4198 macro_rules! check_spendable_outputs {
4199         ($node: expr, $keysinterface: expr) => {
4200                 {
4201                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4202                         let mut txn = Vec::new();
4203                         let mut all_outputs = Vec::new();
4204                         let secp_ctx = Secp256k1::new();
4205                         for event in events.drain(..) {
4206                                 match event {
4207                                         Event::SpendableOutputs { mut outputs } => {
4208                                                 for outp in outputs.drain(..) {
4209                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4210                                                         all_outputs.push(outp);
4211                                                 }
4212                                         },
4213                                         _ => panic!("Unexpected event"),
4214                                 };
4215                         }
4216                         if all_outputs.len() > 1 {
4217                                 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) {
4218                                         txn.push(tx);
4219                                 }
4220                         }
4221                         txn
4222                 }
4223         }
4224 }
4225
4226 #[test]
4227 fn test_claim_sizeable_push_msat() {
4228         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4229         let chanmon_cfgs = create_chanmon_cfgs(2);
4230         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4231         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4232         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4233
4234         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4235         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4236         check_closed_broadcast!(nodes[1], true);
4237         check_added_monitors!(nodes[1], 1);
4238         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4239         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4240         assert_eq!(node_txn.len(), 1);
4241         check_spends!(node_txn[0], chan.3);
4242         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
4243
4244         mine_transaction(&nodes[1], &node_txn[0]);
4245         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4246
4247         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4248         assert_eq!(spend_txn.len(), 1);
4249         assert_eq!(spend_txn[0].input.len(), 1);
4250         check_spends!(spend_txn[0], node_txn[0]);
4251         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4252 }
4253
4254 #[test]
4255 fn test_claim_on_remote_sizeable_push_msat() {
4256         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4257         // to_remote output is encumbered by a P2WPKH
4258         let chanmon_cfgs = create_chanmon_cfgs(2);
4259         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4260         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4261         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4262
4263         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4264         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4265         check_closed_broadcast!(nodes[0], true);
4266         check_added_monitors!(nodes[0], 1);
4267         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4268
4269         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4270         assert_eq!(node_txn.len(), 1);
4271         check_spends!(node_txn[0], chan.3);
4272         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
4273
4274         mine_transaction(&nodes[1], &node_txn[0]);
4275         check_closed_broadcast!(nodes[1], true);
4276         check_added_monitors!(nodes[1], 1);
4277         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4278         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4279
4280         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4281         assert_eq!(spend_txn.len(), 1);
4282         check_spends!(spend_txn[0], node_txn[0]);
4283 }
4284
4285 #[test]
4286 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4287         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4288         // to_remote output is encumbered by a P2WPKH
4289
4290         let chanmon_cfgs = create_chanmon_cfgs(2);
4291         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4292         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4293         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4294
4295         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4296         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4297         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4298         assert_eq!(revoked_local_txn[0].input.len(), 1);
4299         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4300
4301         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4302         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4303         check_closed_broadcast!(nodes[1], true);
4304         check_added_monitors!(nodes[1], 1);
4305         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4306
4307         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4308         mine_transaction(&nodes[1], &node_txn[0]);
4309         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4310
4311         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4312         assert_eq!(spend_txn.len(), 3);
4313         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4314         check_spends!(spend_txn[1], node_txn[0]);
4315         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4316 }
4317
4318 #[test]
4319 fn test_static_spendable_outputs_preimage_tx() {
4320         let chanmon_cfgs = create_chanmon_cfgs(2);
4321         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4322         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4323         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4324
4325         // Create some initial channels
4326         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4327
4328         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4329
4330         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4331         assert_eq!(commitment_tx[0].input.len(), 1);
4332         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4333
4334         // Settle A's commitment tx on B's chain
4335         nodes[1].node.claim_funds(payment_preimage);
4336         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4337         check_added_monitors!(nodes[1], 1);
4338         mine_transaction(&nodes[1], &commitment_tx[0]);
4339         check_added_monitors!(nodes[1], 1);
4340         let events = nodes[1].node.get_and_clear_pending_msg_events();
4341         match events[0] {
4342                 MessageSendEvent::UpdateHTLCs { .. } => {},
4343                 _ => panic!("Unexpected event"),
4344         }
4345         match events[1] {
4346                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4347                 _ => panic!("Unexepected event"),
4348         }
4349
4350         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4351         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4352         assert_eq!(node_txn.len(), 1);
4353         check_spends!(node_txn[0], commitment_tx[0]);
4354         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4355
4356         mine_transaction(&nodes[1], &node_txn[0]);
4357         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4358         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4359
4360         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4361         assert_eq!(spend_txn.len(), 1);
4362         check_spends!(spend_txn[0], node_txn[0]);
4363 }
4364
4365 #[test]
4366 fn test_static_spendable_outputs_timeout_tx() {
4367         let chanmon_cfgs = create_chanmon_cfgs(2);
4368         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4369         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4370         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4371
4372         // Create some initial channels
4373         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4374
4375         // Rebalance the network a bit by relaying one payment through all the channels ...
4376         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4377
4378         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4379
4380         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4381         assert_eq!(commitment_tx[0].input.len(), 1);
4382         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4383
4384         // Settle A's commitment tx on B' chain
4385         mine_transaction(&nodes[1], &commitment_tx[0]);
4386         check_added_monitors!(nodes[1], 1);
4387         let events = nodes[1].node.get_and_clear_pending_msg_events();
4388         match events[0] {
4389                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4390                 _ => panic!("Unexpected event"),
4391         }
4392         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4393
4394         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4395         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4396         assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4397         check_spends!(node_txn[0],  commitment_tx[0].clone());
4398         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4399
4400         mine_transaction(&nodes[1], &node_txn[0]);
4401         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4402         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4403         expect_payment_failed!(nodes[1], our_payment_hash, false);
4404
4405         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4406         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4407         check_spends!(spend_txn[0], commitment_tx[0]);
4408         check_spends!(spend_txn[1], node_txn[0]);
4409         check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4410 }
4411
4412 #[test]
4413 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4414         let chanmon_cfgs = create_chanmon_cfgs(2);
4415         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4416         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4417         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4418
4419         // Create some initial channels
4420         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4421
4422         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4423         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4424         assert_eq!(revoked_local_txn[0].input.len(), 1);
4425         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4426
4427         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4428
4429         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4430         check_closed_broadcast!(nodes[1], true);
4431         check_added_monitors!(nodes[1], 1);
4432         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4433
4434         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4435         assert_eq!(node_txn.len(), 1);
4436         assert_eq!(node_txn[0].input.len(), 2);
4437         check_spends!(node_txn[0], revoked_local_txn[0]);
4438
4439         mine_transaction(&nodes[1], &node_txn[0]);
4440         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4441
4442         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4443         assert_eq!(spend_txn.len(), 1);
4444         check_spends!(spend_txn[0], node_txn[0]);
4445 }
4446
4447 #[test]
4448 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4449         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4450         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4451         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4452         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4453         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4454
4455         // Create some initial channels
4456         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4457
4458         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4459         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4460         assert_eq!(revoked_local_txn[0].input.len(), 1);
4461         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4462
4463         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4464
4465         // A will generate HTLC-Timeout from revoked commitment tx
4466         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4467         check_closed_broadcast!(nodes[0], true);
4468         check_added_monitors!(nodes[0], 1);
4469         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4470         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4471
4472         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4473         assert_eq!(revoked_htlc_txn.len(), 1);
4474         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4475         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4476         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4477         assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4478
4479         // B will generate justice tx from A's revoked commitment/HTLC tx
4480         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4481         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4482         check_closed_broadcast!(nodes[1], true);
4483         check_added_monitors!(nodes[1], 1);
4484         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4485
4486         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4487         assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4488         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4489         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4490         // transactions next...
4491         assert_eq!(node_txn[0].input.len(), 3);
4492         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4493
4494         assert_eq!(node_txn[1].input.len(), 2);
4495         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4496         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4497                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4498         } else {
4499                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4500                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4501         }
4502
4503         mine_transaction(&nodes[1], &node_txn[1]);
4504         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4505
4506         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4507         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4508         assert_eq!(spend_txn.len(), 1);
4509         assert_eq!(spend_txn[0].input.len(), 1);
4510         check_spends!(spend_txn[0], node_txn[1]);
4511 }
4512
4513 #[test]
4514 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4515         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4516         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4517         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4518         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4519         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4520
4521         // Create some initial channels
4522         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4523
4524         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4525         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4526         assert_eq!(revoked_local_txn[0].input.len(), 1);
4527         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4528
4529         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4530         assert_eq!(revoked_local_txn[0].output.len(), 2);
4531
4532         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4533
4534         // B will generate HTLC-Success from revoked commitment tx
4535         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4536         check_closed_broadcast!(nodes[1], true);
4537         check_added_monitors!(nodes[1], 1);
4538         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4539         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4540
4541         assert_eq!(revoked_htlc_txn.len(), 1);
4542         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4543         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4544         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4545
4546         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4547         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4548         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4549
4550         // A will generate justice tx from B's revoked commitment/HTLC tx
4551         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4552         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4553         check_closed_broadcast!(nodes[0], true);
4554         check_added_monitors!(nodes[0], 1);
4555         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4556
4557         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4558         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4559
4560         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4561         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4562         // transactions next...
4563         assert_eq!(node_txn[0].input.len(), 2);
4564         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4565         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4566                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4567         } else {
4568                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4569                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4570         }
4571
4572         assert_eq!(node_txn[1].input.len(), 1);
4573         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4574
4575         mine_transaction(&nodes[0], &node_txn[1]);
4576         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4577
4578         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4579         // didn't try to generate any new transactions.
4580
4581         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4582         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4583         assert_eq!(spend_txn.len(), 3);
4584         assert_eq!(spend_txn[0].input.len(), 1);
4585         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4586         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4587         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4588         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4589 }
4590
4591 #[test]
4592 fn test_onchain_to_onchain_claim() {
4593         // Test that in case of channel closure, we detect the state of output and claim HTLC
4594         // on downstream peer's remote commitment tx.
4595         // First, have C claim an HTLC against its own latest commitment transaction.
4596         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4597         // channel.
4598         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4599         // gets broadcast.
4600
4601         let chanmon_cfgs = create_chanmon_cfgs(3);
4602         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4603         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4604         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4605
4606         // Create some initial channels
4607         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4608         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4609
4610         // Ensure all nodes are at the same height
4611         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4612         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4613         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4614         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4615
4616         // Rebalance the network a bit by relaying one payment through all the channels ...
4617         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4618         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4619
4620         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4621         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4622         check_spends!(commitment_tx[0], chan_2.3);
4623         nodes[2].node.claim_funds(payment_preimage);
4624         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4625         check_added_monitors!(nodes[2], 1);
4626         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4627         assert!(updates.update_add_htlcs.is_empty());
4628         assert!(updates.update_fail_htlcs.is_empty());
4629         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4630         assert!(updates.update_fail_malformed_htlcs.is_empty());
4631
4632         mine_transaction(&nodes[2], &commitment_tx[0]);
4633         check_closed_broadcast!(nodes[2], true);
4634         check_added_monitors!(nodes[2], 1);
4635         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4636
4637         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4638         assert_eq!(c_txn.len(), 1);
4639         check_spends!(c_txn[0], commitment_tx[0]);
4640         assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4641         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4642         assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4643
4644         // 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
4645         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
4646         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone(), c_txn[0].clone()]});
4647         check_added_monitors!(nodes[1], 1);
4648         let events = nodes[1].node.get_and_clear_pending_events();
4649         assert_eq!(events.len(), 2);
4650         match events[0] {
4651                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4652                 _ => panic!("Unexpected event"),
4653         }
4654         match events[1] {
4655                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
4656                         assert_eq!(fee_earned_msat, Some(1000));
4657                         assert_eq!(prev_channel_id, Some(chan_1.2));
4658                         assert_eq!(claim_from_onchain_tx, true);
4659                         assert_eq!(next_channel_id, Some(chan_2.2));
4660                 },
4661                 _ => panic!("Unexpected event"),
4662         }
4663         check_added_monitors!(nodes[1], 1);
4664         let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4665         assert_eq!(msg_events.len(), 3);
4666         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4667         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4668
4669         match nodes_2_event {
4670                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4671                 _ => panic!("Unexpected event"),
4672         }
4673
4674         match nodes_0_event {
4675                 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, .. } } => {
4676                         assert!(update_add_htlcs.is_empty());
4677                         assert!(update_fail_htlcs.is_empty());
4678                         assert_eq!(update_fulfill_htlcs.len(), 1);
4679                         assert!(update_fail_malformed_htlcs.is_empty());
4680                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4681                 },
4682                 _ => panic!("Unexpected event"),
4683         };
4684
4685         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4686         match msg_events[0] {
4687                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4688                 _ => panic!("Unexpected event"),
4689         }
4690
4691         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4692         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4693         mine_transaction(&nodes[1], &commitment_tx[0]);
4694         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4695         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4696         // ChannelMonitor: HTLC-Success tx
4697         assert_eq!(b_txn.len(), 1);
4698         check_spends!(b_txn[0], commitment_tx[0]);
4699         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4700         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4701         assert_eq!(b_txn[0].lock_time.0, 0); // Success tx
4702
4703         check_closed_broadcast!(nodes[1], true);
4704         check_added_monitors!(nodes[1], 1);
4705 }
4706
4707 #[test]
4708 fn test_duplicate_payment_hash_one_failure_one_success() {
4709         // Topology : A --> B --> C --> D
4710         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4711         // Note that because C will refuse to generate two payment secrets for the same payment hash,
4712         // we forward one of the payments onwards to D.
4713         let chanmon_cfgs = create_chanmon_cfgs(4);
4714         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4715         // When this test was written, the default base fee floated based on the HTLC count.
4716         // It is now fixed, so we simply set the fee to the expected value here.
4717         let mut config = test_default_channel_config();
4718         config.channel_config.forwarding_fee_base_msat = 196;
4719         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4720                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4721         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4722
4723         create_announced_chan_between_nodes(&nodes, 0, 1);
4724         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4725         create_announced_chan_between_nodes(&nodes, 2, 3);
4726
4727         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4728         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4729         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4730         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4731         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4732
4733         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4734
4735         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4736         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4737         // script push size limit so that the below script length checks match
4738         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4739         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4740                 .with_features(nodes[3].node.invoice_features());
4741         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000, TEST_FINAL_CLTV - 40);
4742         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4743
4744         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4745         assert_eq!(commitment_txn[0].input.len(), 1);
4746         check_spends!(commitment_txn[0], chan_2.3);
4747
4748         mine_transaction(&nodes[1], &commitment_txn[0]);
4749         check_closed_broadcast!(nodes[1], true);
4750         check_added_monitors!(nodes[1], 1);
4751         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4752         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
4753
4754         let htlc_timeout_tx;
4755         { // Extract one of the two HTLC-Timeout transaction
4756                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4757                 // ChannelMonitor: timeout tx * 2-or-3
4758                 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4759
4760                 check_spends!(node_txn[0], commitment_txn[0]);
4761                 assert_eq!(node_txn[0].input.len(), 1);
4762                 assert_eq!(node_txn[0].output.len(), 1);
4763
4764                 if node_txn.len() > 2 {
4765                         check_spends!(node_txn[1], commitment_txn[0]);
4766                         assert_eq!(node_txn[1].input.len(), 1);
4767                         assert_eq!(node_txn[1].output.len(), 1);
4768                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4769
4770                         check_spends!(node_txn[2], commitment_txn[0]);
4771                         assert_eq!(node_txn[2].input.len(), 1);
4772                         assert_eq!(node_txn[2].output.len(), 1);
4773                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4774                 } else {
4775                         check_spends!(node_txn[1], commitment_txn[0]);
4776                         assert_eq!(node_txn[1].input.len(), 1);
4777                         assert_eq!(node_txn[1].output.len(), 1);
4778                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4779                 }
4780
4781                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4782                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4783                 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
4784                 // (with value 900 sats) will be claimed in the below `claim_funds` call.
4785                 if node_txn.len() > 2 {
4786                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4787                         htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
4788                 } else {
4789                         htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
4790                 }
4791         }
4792
4793         nodes[2].node.claim_funds(our_payment_preimage);
4794         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4795
4796         mine_transaction(&nodes[2], &commitment_txn[0]);
4797         check_added_monitors!(nodes[2], 2);
4798         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4799         let events = nodes[2].node.get_and_clear_pending_msg_events();
4800         match events[0] {
4801                 MessageSendEvent::UpdateHTLCs { .. } => {},
4802                 _ => panic!("Unexpected event"),
4803         }
4804         match events[1] {
4805                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4806                 _ => panic!("Unexepected event"),
4807         }
4808         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4809         assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4810         check_spends!(htlc_success_txn[0], commitment_txn[0]);
4811         check_spends!(htlc_success_txn[1], commitment_txn[0]);
4812         assert_eq!(htlc_success_txn[0].input.len(), 1);
4813         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4814         assert_eq!(htlc_success_txn[1].input.len(), 1);
4815         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4816         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4817         assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4818
4819         mine_transaction(&nodes[1], &htlc_timeout_tx);
4820         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4821         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 }]);
4822         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4823         assert!(htlc_updates.update_add_htlcs.is_empty());
4824         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4825         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4826         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4827         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4828         check_added_monitors!(nodes[1], 1);
4829
4830         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4831         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4832         {
4833                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4834         }
4835         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
4836
4837         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4838         mine_transaction(&nodes[1], &htlc_success_txn[1]);
4839         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
4840         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4841         assert!(updates.update_add_htlcs.is_empty());
4842         assert!(updates.update_fail_htlcs.is_empty());
4843         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4844         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
4845         assert!(updates.update_fail_malformed_htlcs.is_empty());
4846         check_added_monitors!(nodes[1], 1);
4847
4848         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4849         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4850
4851         let events = nodes[0].node.get_and_clear_pending_events();
4852         match events[0] {
4853                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4854                         assert_eq!(*payment_preimage, our_payment_preimage);
4855                         assert_eq!(*payment_hash, duplicate_payment_hash);
4856                 }
4857                 _ => panic!("Unexpected event"),
4858         }
4859 }
4860
4861 #[test]
4862 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4863         let chanmon_cfgs = create_chanmon_cfgs(2);
4864         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4865         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4866         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4867
4868         // Create some initial channels
4869         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4870
4871         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
4872         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4873         assert_eq!(local_txn.len(), 1);
4874         assert_eq!(local_txn[0].input.len(), 1);
4875         check_spends!(local_txn[0], chan_1.3);
4876
4877         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4878         nodes[1].node.claim_funds(payment_preimage);
4879         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
4880         check_added_monitors!(nodes[1], 1);
4881
4882         mine_transaction(&nodes[1], &local_txn[0]);
4883         check_added_monitors!(nodes[1], 1);
4884         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4885         let events = nodes[1].node.get_and_clear_pending_msg_events();
4886         match events[0] {
4887                 MessageSendEvent::UpdateHTLCs { .. } => {},
4888                 _ => panic!("Unexpected event"),
4889         }
4890         match events[1] {
4891                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4892                 _ => panic!("Unexepected event"),
4893         }
4894         let node_tx = {
4895                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4896                 assert_eq!(node_txn.len(), 1);
4897                 assert_eq!(node_txn[0].input.len(), 1);
4898                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4899                 check_spends!(node_txn[0], local_txn[0]);
4900                 node_txn[0].clone()
4901         };
4902
4903         mine_transaction(&nodes[1], &node_tx);
4904         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4905
4906         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4907         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4908         assert_eq!(spend_txn.len(), 1);
4909         assert_eq!(spend_txn[0].input.len(), 1);
4910         check_spends!(spend_txn[0], node_tx);
4911         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4912 }
4913
4914 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4915         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4916         // unrevoked commitment transaction.
4917         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4918         // a remote RAA before they could be failed backwards (and combinations thereof).
4919         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4920         // use the same payment hashes.
4921         // Thus, we use a six-node network:
4922         //
4923         // A \         / E
4924         //    - C - D -
4925         // B /         \ F
4926         // And test where C fails back to A/B when D announces its latest commitment transaction
4927         let chanmon_cfgs = create_chanmon_cfgs(6);
4928         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4929         // When this test was written, the default base fee floated based on the HTLC count.
4930         // It is now fixed, so we simply set the fee to the expected value here.
4931         let mut config = test_default_channel_config();
4932         config.channel_config.forwarding_fee_base_msat = 196;
4933         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
4934                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4935         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4936
4937         let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
4938         let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4939         let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
4940         let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
4941         let chan_3_5  = create_announced_chan_between_nodes(&nodes, 3, 5);
4942
4943         // Rebalance and check output sanity...
4944         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
4945         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
4946         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
4947
4948         let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
4949                 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
4950         // 0th HTLC:
4951         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
4952         // 1st HTLC:
4953         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
4954         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4955         // 2nd HTLC:
4956         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
4957         // 3rd HTLC:
4958         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
4959         // 4th HTLC:
4960         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4961         // 5th HTLC:
4962         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4963         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
4964         // 6th HTLC:
4965         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());
4966         // 7th HTLC:
4967         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());
4968
4969         // 8th HTLC:
4970         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4971         // 9th HTLC:
4972         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4973         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
4974
4975         // 10th HTLC:
4976         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
4977         // 11th HTLC:
4978         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
4979         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());
4980
4981         // Double-check that six of the new HTLC were added
4982         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
4983         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
4984         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
4985         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
4986
4987         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
4988         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
4989         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
4990         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
4991         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
4992         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
4993         check_added_monitors!(nodes[4], 0);
4994
4995         let failed_destinations = vec![
4996                 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
4997                 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
4998                 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
4999                 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5000         ];
5001         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5002         check_added_monitors!(nodes[4], 1);
5003
5004         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5005         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5006         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5007         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5008         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5009         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5010
5011         // Fail 3rd below-dust and 7th above-dust HTLCs
5012         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5013         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5014         check_added_monitors!(nodes[5], 0);
5015
5016         let failed_destinations_2 = vec![
5017                 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5018                 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5019         ];
5020         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5021         check_added_monitors!(nodes[5], 1);
5022
5023         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5024         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5025         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5026         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5027
5028         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5029
5030         // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5031         let failed_destinations_3 = vec![
5032                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5033                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5034                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5035                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5036                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5037                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5038         ];
5039         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5040         check_added_monitors!(nodes[3], 1);
5041         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5042         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5043         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5044         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5045         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5046         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5047         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5048         if deliver_last_raa {
5049                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5050         } else {
5051                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5052         }
5053
5054         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5055         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5056         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5057         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5058         //
5059         // We now broadcast the latest commitment transaction, which *should* result in failures for
5060         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5061         // the non-broadcast above-dust HTLCs.
5062         //
5063         // Alternatively, we may broadcast the previous commitment transaction, which should only
5064         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5065         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5066
5067         if announce_latest {
5068                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5069         } else {
5070                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5071         }
5072         let events = nodes[2].node.get_and_clear_pending_events();
5073         let close_event = if deliver_last_raa {
5074                 assert_eq!(events.len(), 2 + 6);
5075                 events.last().clone().unwrap()
5076         } else {
5077                 assert_eq!(events.len(), 1);
5078                 events.last().clone().unwrap()
5079         };
5080         match close_event {
5081                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5082                 _ => panic!("Unexpected event"),
5083         }
5084
5085         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5086         check_closed_broadcast!(nodes[2], true);
5087         if deliver_last_raa {
5088                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5089
5090                 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();
5091                 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5092         } else {
5093                 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5094                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5095                 } else {
5096                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5097                 };
5098
5099                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5100         }
5101         check_added_monitors!(nodes[2], 3);
5102
5103         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5104         assert_eq!(cs_msgs.len(), 2);
5105         let mut a_done = false;
5106         for msg in cs_msgs {
5107                 match msg {
5108                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5109                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5110                                 // should be failed-backwards here.
5111                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5112                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5113                                         for htlc in &updates.update_fail_htlcs {
5114                                                 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 });
5115                                         }
5116                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5117                                         assert!(!a_done);
5118                                         a_done = true;
5119                                         &nodes[0]
5120                                 } else {
5121                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5122                                         for htlc in &updates.update_fail_htlcs {
5123                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5124                                         }
5125                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5126                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5127                                         &nodes[1]
5128                                 };
5129                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5130                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5131                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5132                                 if announce_latest {
5133                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5134                                         if *node_id == nodes[0].node.get_our_node_id() {
5135                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5136                                         }
5137                                 }
5138                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5139                         },
5140                         _ => panic!("Unexpected event"),
5141                 }
5142         }
5143
5144         let as_events = nodes[0].node.get_and_clear_pending_events();
5145         assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5146         let mut as_failds = HashSet::new();
5147         let mut as_updates = 0;
5148         for event in as_events.iter() {
5149                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5150                         assert!(as_failds.insert(*payment_hash));
5151                         if *payment_hash != payment_hash_2 {
5152                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5153                         } else {
5154                                 assert!(!payment_failed_permanently);
5155                         }
5156                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5157                                 as_updates += 1;
5158                         }
5159                 } else if let &Event::PaymentFailed { .. } = event {
5160                 } else { panic!("Unexpected event"); }
5161         }
5162         assert!(as_failds.contains(&payment_hash_1));
5163         assert!(as_failds.contains(&payment_hash_2));
5164         if announce_latest {
5165                 assert!(as_failds.contains(&payment_hash_3));
5166                 assert!(as_failds.contains(&payment_hash_5));
5167         }
5168         assert!(as_failds.contains(&payment_hash_6));
5169
5170         let bs_events = nodes[1].node.get_and_clear_pending_events();
5171         assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5172         let mut bs_failds = HashSet::new();
5173         let mut bs_updates = 0;
5174         for event in bs_events.iter() {
5175                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5176                         assert!(bs_failds.insert(*payment_hash));
5177                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5178                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5179                         } else {
5180                                 assert!(!payment_failed_permanently);
5181                         }
5182                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5183                                 bs_updates += 1;
5184                         }
5185                 } else if let &Event::PaymentFailed { .. } = event {
5186                 } else { panic!("Unexpected event"); }
5187         }
5188         assert!(bs_failds.contains(&payment_hash_1));
5189         assert!(bs_failds.contains(&payment_hash_2));
5190         if announce_latest {
5191                 assert!(bs_failds.contains(&payment_hash_4));
5192         }
5193         assert!(bs_failds.contains(&payment_hash_5));
5194
5195         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5196         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5197         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5198         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5199         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5200         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5201 }
5202
5203 #[test]
5204 fn test_fail_backwards_latest_remote_announce_a() {
5205         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5206 }
5207
5208 #[test]
5209 fn test_fail_backwards_latest_remote_announce_b() {
5210         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5211 }
5212
5213 #[test]
5214 fn test_fail_backwards_previous_remote_announce() {
5215         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5216         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5217         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5218 }
5219
5220 #[test]
5221 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5222         let chanmon_cfgs = create_chanmon_cfgs(2);
5223         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5224         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5225         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5226
5227         // Create some initial channels
5228         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5229
5230         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5231         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5232         assert_eq!(local_txn[0].input.len(), 1);
5233         check_spends!(local_txn[0], chan_1.3);
5234
5235         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5236         mine_transaction(&nodes[0], &local_txn[0]);
5237         check_closed_broadcast!(nodes[0], true);
5238         check_added_monitors!(nodes[0], 1);
5239         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5240         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5241
5242         let htlc_timeout = {
5243                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5244                 assert_eq!(node_txn.len(), 1);
5245                 assert_eq!(node_txn[0].input.len(), 1);
5246                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5247                 check_spends!(node_txn[0], local_txn[0]);
5248                 node_txn[0].clone()
5249         };
5250
5251         mine_transaction(&nodes[0], &htlc_timeout);
5252         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5253         expect_payment_failed!(nodes[0], our_payment_hash, false);
5254
5255         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5256         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5257         assert_eq!(spend_txn.len(), 3);
5258         check_spends!(spend_txn[0], local_txn[0]);
5259         assert_eq!(spend_txn[1].input.len(), 1);
5260         check_spends!(spend_txn[1], htlc_timeout);
5261         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5262         assert_eq!(spend_txn[2].input.len(), 2);
5263         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5264         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5265                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5266 }
5267
5268 #[test]
5269 fn test_key_derivation_params() {
5270         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5271         // manager rotation to test that `channel_keys_id` returned in
5272         // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5273         // then derive a `delayed_payment_key`.
5274
5275         let chanmon_cfgs = create_chanmon_cfgs(3);
5276
5277         // We manually create the node configuration to backup the seed.
5278         let seed = [42; 32];
5279         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5280         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);
5281         let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5282         let scorer = Mutex::new(test_utils::TestScorer::new());
5283         let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5284         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)) };
5285         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5286         node_cfgs.remove(0);
5287         node_cfgs.insert(0, node);
5288
5289         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5290         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5291
5292         // Create some initial channels
5293         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5294         // for node 0
5295         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5296         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5297         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5298
5299         // Ensure all nodes are at the same height
5300         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5301         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5302         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5303         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5304
5305         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5306         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5307         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5308         assert_eq!(local_txn_1[0].input.len(), 1);
5309         check_spends!(local_txn_1[0], chan_1.3);
5310
5311         // We check funding pubkey are unique
5312         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]));
5313         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]));
5314         if from_0_funding_key_0 == from_1_funding_key_0
5315             || from_0_funding_key_0 == from_1_funding_key_1
5316             || from_0_funding_key_1 == from_1_funding_key_0
5317             || from_0_funding_key_1 == from_1_funding_key_1 {
5318                 panic!("Funding pubkeys aren't unique");
5319         }
5320
5321         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5322         mine_transaction(&nodes[0], &local_txn_1[0]);
5323         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5324         check_closed_broadcast!(nodes[0], true);
5325         check_added_monitors!(nodes[0], 1);
5326         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5327
5328         let htlc_timeout = {
5329                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5330                 assert_eq!(node_txn.len(), 1);
5331                 assert_eq!(node_txn[0].input.len(), 1);
5332                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5333                 check_spends!(node_txn[0], local_txn_1[0]);
5334                 node_txn[0].clone()
5335         };
5336
5337         mine_transaction(&nodes[0], &htlc_timeout);
5338         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5339         expect_payment_failed!(nodes[0], our_payment_hash, false);
5340
5341         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5342         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5343         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5344         assert_eq!(spend_txn.len(), 3);
5345         check_spends!(spend_txn[0], local_txn_1[0]);
5346         assert_eq!(spend_txn[1].input.len(), 1);
5347         check_spends!(spend_txn[1], htlc_timeout);
5348         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5349         assert_eq!(spend_txn[2].input.len(), 2);
5350         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5351         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5352                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5353 }
5354
5355 #[test]
5356 fn test_static_output_closing_tx() {
5357         let chanmon_cfgs = create_chanmon_cfgs(2);
5358         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5359         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5360         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5361
5362         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5363
5364         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5365         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5366
5367         mine_transaction(&nodes[0], &closing_tx);
5368         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5369         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5370
5371         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5372         assert_eq!(spend_txn.len(), 1);
5373         check_spends!(spend_txn[0], closing_tx);
5374
5375         mine_transaction(&nodes[1], &closing_tx);
5376         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5377         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5378
5379         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5380         assert_eq!(spend_txn.len(), 1);
5381         check_spends!(spend_txn[0], closing_tx);
5382 }
5383
5384 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5385         let chanmon_cfgs = create_chanmon_cfgs(2);
5386         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5387         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5388         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5389         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5390
5391         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5392
5393         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5394         // present in B's local commitment transaction, but none of A's commitment transactions.
5395         nodes[1].node.claim_funds(payment_preimage);
5396         check_added_monitors!(nodes[1], 1);
5397         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5398
5399         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5400         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5401         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5402
5403         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5404         check_added_monitors!(nodes[0], 1);
5405         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5406         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5407         check_added_monitors!(nodes[1], 1);
5408
5409         let starting_block = nodes[1].best_block_info();
5410         let mut block = Block {
5411                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5412                 txdata: vec![],
5413         };
5414         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5415                 connect_block(&nodes[1], &block);
5416                 block.header.prev_blockhash = block.block_hash();
5417         }
5418         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5419         check_closed_broadcast!(nodes[1], true);
5420         check_added_monitors!(nodes[1], 1);
5421         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5422 }
5423
5424 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5425         let chanmon_cfgs = create_chanmon_cfgs(2);
5426         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5427         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5428         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5429         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5430
5431         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5432         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
5433         check_added_monitors!(nodes[0], 1);
5434
5435         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5436
5437         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5438         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5439         // to "time out" the HTLC.
5440
5441         let starting_block = nodes[1].best_block_info();
5442         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5443
5444         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5445                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5446                 header.prev_blockhash = header.block_hash();
5447         }
5448         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5449         check_closed_broadcast!(nodes[0], true);
5450         check_added_monitors!(nodes[0], 1);
5451         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5452 }
5453
5454 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5455         let chanmon_cfgs = create_chanmon_cfgs(3);
5456         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5457         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5458         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5459         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5460
5461         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5462         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5463         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5464         // actually revoked.
5465         let htlc_value = if use_dust { 50000 } else { 3000000 };
5466         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5467         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5468         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5469         check_added_monitors!(nodes[1], 1);
5470
5471         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5472         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5473         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5474         check_added_monitors!(nodes[0], 1);
5475         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5476         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5477         check_added_monitors!(nodes[1], 1);
5478         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5479         check_added_monitors!(nodes[1], 1);
5480         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5481
5482         if check_revoke_no_close {
5483                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5484                 check_added_monitors!(nodes[0], 1);
5485         }
5486
5487         let starting_block = nodes[1].best_block_info();
5488         let mut block = Block {
5489                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5490                 txdata: vec![],
5491         };
5492         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5493                 connect_block(&nodes[0], &block);
5494                 block.header.prev_blockhash = block.block_hash();
5495         }
5496         if !check_revoke_no_close {
5497                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5498                 check_closed_broadcast!(nodes[0], true);
5499                 check_added_monitors!(nodes[0], 1);
5500                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5501         } else {
5502                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5503         }
5504 }
5505
5506 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5507 // There are only a few cases to test here:
5508 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5509 //    broadcastable commitment transactions result in channel closure,
5510 //  * its included in an unrevoked-but-previous remote commitment transaction,
5511 //  * its included in the latest remote or local commitment transactions.
5512 // We test each of the three possible commitment transactions individually and use both dust and
5513 // non-dust HTLCs.
5514 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5515 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5516 // tested for at least one of the cases in other tests.
5517 #[test]
5518 fn htlc_claim_single_commitment_only_a() {
5519         do_htlc_claim_local_commitment_only(true);
5520         do_htlc_claim_local_commitment_only(false);
5521
5522         do_htlc_claim_current_remote_commitment_only(true);
5523         do_htlc_claim_current_remote_commitment_only(false);
5524 }
5525
5526 #[test]
5527 fn htlc_claim_single_commitment_only_b() {
5528         do_htlc_claim_previous_remote_commitment_only(true, false);
5529         do_htlc_claim_previous_remote_commitment_only(false, false);
5530         do_htlc_claim_previous_remote_commitment_only(true, true);
5531         do_htlc_claim_previous_remote_commitment_only(false, true);
5532 }
5533
5534 #[test]
5535 #[should_panic]
5536 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5537         let chanmon_cfgs = create_chanmon_cfgs(2);
5538         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5539         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5540         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5541         // Force duplicate randomness for every get-random call
5542         for node in nodes.iter() {
5543                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5544         }
5545
5546         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5547         let channel_value_satoshis=10000;
5548         let push_msat=10001;
5549         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5550         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5551         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5552         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5553
5554         // Create a second channel with the same random values. This used to panic due to a colliding
5555         // channel_id, but now panics due to a colliding outbound SCID alias.
5556         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5557 }
5558
5559 #[test]
5560 fn bolt2_open_channel_sending_node_checks_part2() {
5561         let chanmon_cfgs = create_chanmon_cfgs(2);
5562         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5563         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5564         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5565
5566         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5567         let channel_value_satoshis=2^24;
5568         let push_msat=10001;
5569         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5570
5571         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5572         let channel_value_satoshis=10000;
5573         // Test when push_msat is equal to 1000 * funding_satoshis.
5574         let push_msat=1000*channel_value_satoshis+1;
5575         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5576
5577         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5578         let channel_value_satoshis=10000;
5579         let push_msat=10001;
5580         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
5581         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5582         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5583
5584         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5585         // 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
5586         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5587
5588         // 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.
5589         assert!(BREAKDOWN_TIMEOUT>0);
5590         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5591
5592         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5593         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5594         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5595
5596         // 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.
5597         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5598         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5599         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5600         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5601         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5602 }
5603
5604 #[test]
5605 fn bolt2_open_channel_sane_dust_limit() {
5606         let chanmon_cfgs = create_chanmon_cfgs(2);
5607         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5608         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5609         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5610
5611         let channel_value_satoshis=1000000;
5612         let push_msat=10001;
5613         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5614         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5615         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5616         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5617
5618         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5619         let events = nodes[1].node.get_and_clear_pending_msg_events();
5620         let err_msg = match events[0] {
5621                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5622                         msg.clone()
5623                 },
5624                 _ => panic!("Unexpected event"),
5625         };
5626         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5627 }
5628
5629 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5630 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5631 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5632 // is no longer affordable once it's freed.
5633 #[test]
5634 fn test_fail_holding_cell_htlc_upon_free() {
5635         let chanmon_cfgs = create_chanmon_cfgs(2);
5636         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5637         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5638         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5639         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5640
5641         // First nodes[0] generates an update_fee, setting the channel's
5642         // pending_update_fee.
5643         {
5644                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5645                 *feerate_lock += 20;
5646         }
5647         nodes[0].node.timer_tick_occurred();
5648         check_added_monitors!(nodes[0], 1);
5649
5650         let events = nodes[0].node.get_and_clear_pending_msg_events();
5651         assert_eq!(events.len(), 1);
5652         let (update_msg, commitment_signed) = match events[0] {
5653                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5654                         (update_fee.as_ref(), commitment_signed)
5655                 },
5656                 _ => panic!("Unexpected event"),
5657         };
5658
5659         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5660
5661         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5662         let channel_reserve = chan_stat.channel_reserve_msat;
5663         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5664         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5665
5666         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5667         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5668         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5669
5670         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5671         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5672         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5673         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5674
5675         // Flush the pending fee update.
5676         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5677         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5678         check_added_monitors!(nodes[1], 1);
5679         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5680         check_added_monitors!(nodes[0], 1);
5681
5682         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5683         // HTLC, but now that the fee has been raised the payment will now fail, causing
5684         // us to surface its failure to the user.
5685         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5686         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5687         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);
5688         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 {}",
5689                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5690         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5691
5692         // Check that the payment failed to be sent out.
5693         let events = nodes[0].node.get_and_clear_pending_events();
5694         assert_eq!(events.len(), 2);
5695         match &events[0] {
5696                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5697                         assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5698                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5699                         assert_eq!(*payment_failed_permanently, false);
5700                         assert_eq!(*short_channel_id, Some(route.paths[0][0].short_channel_id));
5701                 },
5702                 _ => panic!("Unexpected event"),
5703         }
5704         match &events[1] {
5705                 &Event::PaymentFailed { ref payment_hash, .. } => {
5706                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5707                 },
5708                 _ => panic!("Unexpected event"),
5709         }
5710 }
5711
5712 // Test that if multiple HTLCs are released from the holding cell and one is
5713 // valid but the other is no longer valid upon release, the valid HTLC can be
5714 // successfully completed while the other one fails as expected.
5715 #[test]
5716 fn test_free_and_fail_holding_cell_htlcs() {
5717         let chanmon_cfgs = create_chanmon_cfgs(2);
5718         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5719         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5720         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5721         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5722
5723         // First nodes[0] generates an update_fee, setting the channel's
5724         // pending_update_fee.
5725         {
5726                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5727                 *feerate_lock += 200;
5728         }
5729         nodes[0].node.timer_tick_occurred();
5730         check_added_monitors!(nodes[0], 1);
5731
5732         let events = nodes[0].node.get_and_clear_pending_msg_events();
5733         assert_eq!(events.len(), 1);
5734         let (update_msg, commitment_signed) = match events[0] {
5735                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5736                         (update_fee.as_ref(), commitment_signed)
5737                 },
5738                 _ => panic!("Unexpected event"),
5739         };
5740
5741         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5742
5743         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5744         let channel_reserve = chan_stat.channel_reserve_msat;
5745         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5746         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5747
5748         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5749         let amt_1 = 20000;
5750         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
5751         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5752         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5753
5754         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5755         nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5756         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5757         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5758         let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5759         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2), payment_id_2).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 + amt_2);
5762
5763         // Flush the pending fee update.
5764         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5765         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5766         check_added_monitors!(nodes[1], 1);
5767         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5768         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5769         check_added_monitors!(nodes[0], 2);
5770
5771         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5772         // but now that the fee has been raised the second payment will now fail, causing us
5773         // to surface its failure to the user. The first payment should succeed.
5774         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5775         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5776         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);
5777         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 {}",
5778                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5779         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5780
5781         // Check that the second payment failed to be sent out.
5782         let events = nodes[0].node.get_and_clear_pending_events();
5783         assert_eq!(events.len(), 2);
5784         match &events[0] {
5785                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5786                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5787                         assert_eq!(payment_hash_2.clone(), *payment_hash);
5788                         assert_eq!(*payment_failed_permanently, false);
5789                         assert_eq!(*short_channel_id, Some(route_2.paths[0][0].short_channel_id));
5790                 },
5791                 _ => panic!("Unexpected event"),
5792         }
5793         match &events[1] {
5794                 &Event::PaymentFailed { ref payment_hash, .. } => {
5795                         assert_eq!(payment_hash_2.clone(), *payment_hash);
5796                 },
5797                 _ => panic!("Unexpected event"),
5798         }
5799
5800         // Complete the first payment and the RAA from the fee update.
5801         let (payment_event, send_raa_event) = {
5802                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5803                 assert_eq!(msgs.len(), 2);
5804                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5805         };
5806         let raa = match send_raa_event {
5807                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5808                 _ => panic!("Unexpected event"),
5809         };
5810         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5811         check_added_monitors!(nodes[1], 1);
5812         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5813         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5814         let events = nodes[1].node.get_and_clear_pending_events();
5815         assert_eq!(events.len(), 1);
5816         match events[0] {
5817                 Event::PendingHTLCsForwardable { .. } => {},
5818                 _ => panic!("Unexpected event"),
5819         }
5820         nodes[1].node.process_pending_htlc_forwards();
5821         let events = nodes[1].node.get_and_clear_pending_events();
5822         assert_eq!(events.len(), 1);
5823         match events[0] {
5824                 Event::PaymentClaimable { .. } => {},
5825                 _ => panic!("Unexpected event"),
5826         }
5827         nodes[1].node.claim_funds(payment_preimage_1);
5828         check_added_monitors!(nodes[1], 1);
5829         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5830
5831         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5832         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5833         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5834         expect_payment_sent!(nodes[0], payment_preimage_1);
5835 }
5836
5837 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
5838 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
5839 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
5840 // once it's freed.
5841 #[test]
5842 fn test_fail_holding_cell_htlc_upon_free_multihop() {
5843         let chanmon_cfgs = create_chanmon_cfgs(3);
5844         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5845         // When this test was written, the default base fee floated based on the HTLC count.
5846         // It is now fixed, so we simply set the fee to the expected value here.
5847         let mut config = test_default_channel_config();
5848         config.channel_config.forwarding_fee_base_msat = 196;
5849         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5850         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5851         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5852         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
5853
5854         // First nodes[1] generates an update_fee, setting the channel's
5855         // pending_update_fee.
5856         {
5857                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
5858                 *feerate_lock += 20;
5859         }
5860         nodes[1].node.timer_tick_occurred();
5861         check_added_monitors!(nodes[1], 1);
5862
5863         let events = nodes[1].node.get_and_clear_pending_msg_events();
5864         assert_eq!(events.len(), 1);
5865         let (update_msg, commitment_signed) = match events[0] {
5866                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5867                         (update_fee.as_ref(), commitment_signed)
5868                 },
5869                 _ => panic!("Unexpected event"),
5870         };
5871
5872         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
5873
5874         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
5875         let channel_reserve = chan_stat.channel_reserve_msat;
5876         let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
5877         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_0_1.2);
5878
5879         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5880         let feemsat = 239;
5881         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
5882         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
5883         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
5884         let payment_event = {
5885                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5886                 check_added_monitors!(nodes[0], 1);
5887
5888                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5889                 assert_eq!(events.len(), 1);
5890
5891                 SendEvent::from_event(events.remove(0))
5892         };
5893         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5894         check_added_monitors!(nodes[1], 0);
5895         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5896         expect_pending_htlcs_forwardable!(nodes[1]);
5897
5898         chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
5899         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5900
5901         // Flush the pending fee update.
5902         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
5903         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5904         check_added_monitors!(nodes[2], 1);
5905         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
5906         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
5907         check_added_monitors!(nodes[1], 2);
5908
5909         // A final RAA message is generated to finalize the fee update.
5910         let events = nodes[1].node.get_and_clear_pending_msg_events();
5911         assert_eq!(events.len(), 1);
5912
5913         let raa_msg = match &events[0] {
5914                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
5915                         msg.clone()
5916                 },
5917                 _ => panic!("Unexpected event"),
5918         };
5919
5920         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
5921         check_added_monitors!(nodes[2], 1);
5922         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
5923
5924         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
5925         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
5926         assert_eq!(process_htlc_forwards_event.len(), 2);
5927         match &process_htlc_forwards_event[0] {
5928                 &Event::PendingHTLCsForwardable { .. } => {},
5929                 _ => panic!("Unexpected event"),
5930         }
5931
5932         // In response, we call ChannelManager's process_pending_htlc_forwards
5933         nodes[1].node.process_pending_htlc_forwards();
5934         check_added_monitors!(nodes[1], 1);
5935
5936         // This causes the HTLC to be failed backwards.
5937         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
5938         assert_eq!(fail_event.len(), 1);
5939         let (fail_msg, commitment_signed) = match &fail_event[0] {
5940                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
5941                         assert_eq!(updates.update_add_htlcs.len(), 0);
5942                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
5943                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
5944                         assert_eq!(updates.update_fail_htlcs.len(), 1);
5945                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
5946                 },
5947                 _ => panic!("Unexpected event"),
5948         };
5949
5950         // Pass the failure messages back to nodes[0].
5951         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5952         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5953
5954         // Complete the HTLC failure+removal process.
5955         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5956         check_added_monitors!(nodes[0], 1);
5957         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5958         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
5959         check_added_monitors!(nodes[1], 2);
5960         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
5961         assert_eq!(final_raa_event.len(), 1);
5962         let raa = match &final_raa_event[0] {
5963                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
5964                 _ => panic!("Unexpected event"),
5965         };
5966         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
5967         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
5968         check_added_monitors!(nodes[0], 1);
5969 }
5970
5971 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
5972 // 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.
5973 //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.
5974
5975 #[test]
5976 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
5977         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
5978         let chanmon_cfgs = create_chanmon_cfgs(2);
5979         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5980         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5981         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5982         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5983
5984         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
5985         route.paths[0][0].fee_msat = 100;
5986
5987         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 },
5988                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
5989         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5990         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
5991 }
5992
5993 #[test]
5994 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
5995         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
5996         let chanmon_cfgs = create_chanmon_cfgs(2);
5997         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5998         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5999         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6000         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6001
6002         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6003         route.paths[0][0].fee_msat = 0;
6004         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 },
6005                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6006
6007         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6008         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6009 }
6010
6011 #[test]
6012 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6013         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6014         let chanmon_cfgs = create_chanmon_cfgs(2);
6015         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6016         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6017         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6018         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6019
6020         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6021         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6022         check_added_monitors!(nodes[0], 1);
6023         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6024         updates.update_add_htlcs[0].amount_msat = 0;
6025
6026         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6027         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6028         check_closed_broadcast!(nodes[1], true).unwrap();
6029         check_added_monitors!(nodes[1], 1);
6030         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6031 }
6032
6033 #[test]
6034 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6035         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6036         //It is enforced when constructing a route.
6037         let chanmon_cfgs = create_chanmon_cfgs(2);
6038         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6039         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6040         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6041         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6042
6043         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6044                 .with_features(nodes[1].node.invoice_features());
6045         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6046         route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6047         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 },
6048                 assert_eq!(err, &"Channel CLTV overflowed?"));
6049 }
6050
6051 #[test]
6052 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6053         //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.
6054         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6055         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6056         let chanmon_cfgs = create_chanmon_cfgs(2);
6057         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6058         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6059         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6060         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6061         let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6062                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6063
6064         for i in 0..max_accepted_htlcs {
6065                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6066                 let payment_event = {
6067                         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6068                         check_added_monitors!(nodes[0], 1);
6069
6070                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6071                         assert_eq!(events.len(), 1);
6072                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6073                                 assert_eq!(htlcs[0].htlc_id, i);
6074                         } else {
6075                                 assert!(false);
6076                         }
6077                         SendEvent::from_event(events.remove(0))
6078                 };
6079                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6080                 check_added_monitors!(nodes[1], 0);
6081                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6082
6083                 expect_pending_htlcs_forwardable!(nodes[1]);
6084                 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6085         }
6086         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6087         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 },
6088                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6089
6090         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6091         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6092 }
6093
6094 #[test]
6095 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6096         //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.
6097         let chanmon_cfgs = create_chanmon_cfgs(2);
6098         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6099         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6100         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6101         let channel_value = 100000;
6102         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6103         let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6104
6105         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6106
6107         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6108         // Manually create a route over our max in flight (which our router normally automatically
6109         // limits us to.
6110         route.paths[0][0].fee_msat =  max_in_flight + 1;
6111         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 },
6112                 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)));
6113
6114         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6115         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over the max HTLC value in flight our peer will accept".to_string(), 1);
6116
6117         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6118 }
6119
6120 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6121 #[test]
6122 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6123         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6124         let chanmon_cfgs = create_chanmon_cfgs(2);
6125         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6126         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6127         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6128         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6129         let htlc_minimum_msat: u64;
6130         {
6131                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6132                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6133                 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6134                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6135         }
6136
6137         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6138         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6139         check_added_monitors!(nodes[0], 1);
6140         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6141         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6142         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6143         assert!(nodes[1].node.list_channels().is_empty());
6144         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6145         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()));
6146         check_added_monitors!(nodes[1], 1);
6147         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6148 }
6149
6150 #[test]
6151 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6152         //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
6153         let chanmon_cfgs = create_chanmon_cfgs(2);
6154         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6155         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6156         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6157         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6158
6159         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6160         let channel_reserve = chan_stat.channel_reserve_msat;
6161         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6162         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
6163         // The 2* and +1 are for the fee spike reserve.
6164         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6165
6166         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6167         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6168         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6169         check_added_monitors!(nodes[0], 1);
6170         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6171
6172         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6173         // at this time channel-initiatee receivers are not required to enforce that senders
6174         // respect the fee_spike_reserve.
6175         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6176         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6177
6178         assert!(nodes[1].node.list_channels().is_empty());
6179         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6180         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6181         check_added_monitors!(nodes[1], 1);
6182         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6183 }
6184
6185 #[test]
6186 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6187         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6188         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6189         let chanmon_cfgs = create_chanmon_cfgs(2);
6190         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6191         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6192         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6193         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6194
6195         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6196         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6197         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6198         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6199         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6200         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6201
6202         let mut msg = msgs::UpdateAddHTLC {
6203                 channel_id: chan.2,
6204                 htlc_id: 0,
6205                 amount_msat: 1000,
6206                 payment_hash: our_payment_hash,
6207                 cltv_expiry: htlc_cltv,
6208                 onion_routing_packet: onion_packet.clone(),
6209         };
6210
6211         for i in 0..super::channel::OUR_MAX_HTLCS {
6212                 msg.htlc_id = i as u64;
6213                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6214         }
6215         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6216         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6217
6218         assert!(nodes[1].node.list_channels().is_empty());
6219         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6220         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6221         check_added_monitors!(nodes[1], 1);
6222         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6223 }
6224
6225 #[test]
6226 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6227         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6228         let chanmon_cfgs = create_chanmon_cfgs(2);
6229         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6230         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6231         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6232         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6233
6234         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6235         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6236         check_added_monitors!(nodes[0], 1);
6237         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6238         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;
6239         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6240
6241         assert!(nodes[1].node.list_channels().is_empty());
6242         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6243         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6244         check_added_monitors!(nodes[1], 1);
6245         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6246 }
6247
6248 #[test]
6249 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6250         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6251         let chanmon_cfgs = create_chanmon_cfgs(2);
6252         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6253         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6254         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6255
6256         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6257         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6258         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6259         check_added_monitors!(nodes[0], 1);
6260         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6261         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6262         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6263
6264         assert!(nodes[1].node.list_channels().is_empty());
6265         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6266         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6267         check_added_monitors!(nodes[1], 1);
6268         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6269 }
6270
6271 #[test]
6272 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6273         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6274         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6275         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6276         let chanmon_cfgs = create_chanmon_cfgs(2);
6277         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6278         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6279         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6280
6281         create_announced_chan_between_nodes(&nodes, 0, 1);
6282         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6283         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6284         check_added_monitors!(nodes[0], 1);
6285         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6286         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6287
6288         //Disconnect and Reconnect
6289         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6290         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6291         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();
6292         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6293         assert_eq!(reestablish_1.len(), 1);
6294         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();
6295         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6296         assert_eq!(reestablish_2.len(), 1);
6297         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6298         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6299         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6300         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6301
6302         //Resend HTLC
6303         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6304         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6305         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6306         check_added_monitors!(nodes[1], 1);
6307         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6308
6309         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6310
6311         assert!(nodes[1].node.list_channels().is_empty());
6312         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6313         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6314         check_added_monitors!(nodes[1], 1);
6315         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6316 }
6317
6318 #[test]
6319 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6320         //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.
6321
6322         let chanmon_cfgs = create_chanmon_cfgs(2);
6323         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6324         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6325         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6326         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6327         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6328         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6329
6330         check_added_monitors!(nodes[0], 1);
6331         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6332         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6333
6334         let update_msg = msgs::UpdateFulfillHTLC{
6335                 channel_id: chan.2,
6336                 htlc_id: 0,
6337                 payment_preimage: our_payment_preimage,
6338         };
6339
6340         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6341
6342         assert!(nodes[0].node.list_channels().is_empty());
6343         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6344         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()));
6345         check_added_monitors!(nodes[0], 1);
6346         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6347 }
6348
6349 #[test]
6350 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6351         //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.
6352
6353         let chanmon_cfgs = create_chanmon_cfgs(2);
6354         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6355         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6356         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6357         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6358
6359         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6360         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6361         check_added_monitors!(nodes[0], 1);
6362         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6363         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6364
6365         let update_msg = msgs::UpdateFailHTLC{
6366                 channel_id: chan.2,
6367                 htlc_id: 0,
6368                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6369         };
6370
6371         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6372
6373         assert!(nodes[0].node.list_channels().is_empty());
6374         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6375         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()));
6376         check_added_monitors!(nodes[0], 1);
6377         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6378 }
6379
6380 #[test]
6381 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6382         //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.
6383
6384         let chanmon_cfgs = create_chanmon_cfgs(2);
6385         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6386         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6387         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6388         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6389
6390         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6391         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6392         check_added_monitors!(nodes[0], 1);
6393         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6394         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6395         let update_msg = msgs::UpdateFailMalformedHTLC{
6396                 channel_id: chan.2,
6397                 htlc_id: 0,
6398                 sha256_of_onion: [1; 32],
6399                 failure_code: 0x8000,
6400         };
6401
6402         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6403
6404         assert!(nodes[0].node.list_channels().is_empty());
6405         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6406         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()));
6407         check_added_monitors!(nodes[0], 1);
6408         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6409 }
6410
6411 #[test]
6412 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6413         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6414
6415         let chanmon_cfgs = create_chanmon_cfgs(2);
6416         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6417         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6418         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6419         create_announced_chan_between_nodes(&nodes, 0, 1);
6420
6421         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6422
6423         nodes[1].node.claim_funds(our_payment_preimage);
6424         check_added_monitors!(nodes[1], 1);
6425         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6426
6427         let events = nodes[1].node.get_and_clear_pending_msg_events();
6428         assert_eq!(events.len(), 1);
6429         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6430                 match events[0] {
6431                         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, .. } } => {
6432                                 assert!(update_add_htlcs.is_empty());
6433                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6434                                 assert!(update_fail_htlcs.is_empty());
6435                                 assert!(update_fail_malformed_htlcs.is_empty());
6436                                 assert!(update_fee.is_none());
6437                                 update_fulfill_htlcs[0].clone()
6438                         },
6439                         _ => panic!("Unexpected event"),
6440                 }
6441         };
6442
6443         update_fulfill_msg.htlc_id = 1;
6444
6445         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6446
6447         assert!(nodes[0].node.list_channels().is_empty());
6448         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6449         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6450         check_added_monitors!(nodes[0], 1);
6451         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6452 }
6453
6454 #[test]
6455 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6456         //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.
6457
6458         let chanmon_cfgs = create_chanmon_cfgs(2);
6459         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6460         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6461         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6462         create_announced_chan_between_nodes(&nodes, 0, 1);
6463
6464         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6465
6466         nodes[1].node.claim_funds(our_payment_preimage);
6467         check_added_monitors!(nodes[1], 1);
6468         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6469
6470         let events = nodes[1].node.get_and_clear_pending_msg_events();
6471         assert_eq!(events.len(), 1);
6472         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6473                 match events[0] {
6474                         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, .. } } => {
6475                                 assert!(update_add_htlcs.is_empty());
6476                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6477                                 assert!(update_fail_htlcs.is_empty());
6478                                 assert!(update_fail_malformed_htlcs.is_empty());
6479                                 assert!(update_fee.is_none());
6480                                 update_fulfill_htlcs[0].clone()
6481                         },
6482                         _ => panic!("Unexpected event"),
6483                 }
6484         };
6485
6486         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6487
6488         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6489
6490         assert!(nodes[0].node.list_channels().is_empty());
6491         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6492         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6493         check_added_monitors!(nodes[0], 1);
6494         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6495 }
6496
6497 #[test]
6498 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6499         //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.
6500
6501         let chanmon_cfgs = create_chanmon_cfgs(2);
6502         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6503         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6504         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6505         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6506
6507         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6508         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6509         check_added_monitors!(nodes[0], 1);
6510
6511         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6512         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6513
6514         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6515         check_added_monitors!(nodes[1], 0);
6516         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6517
6518         let events = nodes[1].node.get_and_clear_pending_msg_events();
6519
6520         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6521                 match events[0] {
6522                         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, .. } } => {
6523                                 assert!(update_add_htlcs.is_empty());
6524                                 assert!(update_fulfill_htlcs.is_empty());
6525                                 assert!(update_fail_htlcs.is_empty());
6526                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6527                                 assert!(update_fee.is_none());
6528                                 update_fail_malformed_htlcs[0].clone()
6529                         },
6530                         _ => panic!("Unexpected event"),
6531                 }
6532         };
6533         update_msg.failure_code &= !0x8000;
6534         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6535
6536         assert!(nodes[0].node.list_channels().is_empty());
6537         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6538         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6539         check_added_monitors!(nodes[0], 1);
6540         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6541 }
6542
6543 #[test]
6544 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6545         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6546         //    * 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.
6547
6548         let chanmon_cfgs = create_chanmon_cfgs(3);
6549         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6550         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6551         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6552         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6553         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6554
6555         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6556
6557         //First hop
6558         let mut payment_event = {
6559                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6560                 check_added_monitors!(nodes[0], 1);
6561                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6562                 assert_eq!(events.len(), 1);
6563                 SendEvent::from_event(events.remove(0))
6564         };
6565         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6566         check_added_monitors!(nodes[1], 0);
6567         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6568         expect_pending_htlcs_forwardable!(nodes[1]);
6569         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6570         assert_eq!(events_2.len(), 1);
6571         check_added_monitors!(nodes[1], 1);
6572         payment_event = SendEvent::from_event(events_2.remove(0));
6573         assert_eq!(payment_event.msgs.len(), 1);
6574
6575         //Second Hop
6576         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6577         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6578         check_added_monitors!(nodes[2], 0);
6579         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6580
6581         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6582         assert_eq!(events_3.len(), 1);
6583         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6584                 match events_3[0] {
6585                         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 } } => {
6586                                 assert!(update_add_htlcs.is_empty());
6587                                 assert!(update_fulfill_htlcs.is_empty());
6588                                 assert!(update_fail_htlcs.is_empty());
6589                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6590                                 assert!(update_fee.is_none());
6591                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6592                         },
6593                         _ => panic!("Unexpected event"),
6594                 }
6595         };
6596
6597         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6598
6599         check_added_monitors!(nodes[1], 0);
6600         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6601         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 }]);
6602         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6603         assert_eq!(events_4.len(), 1);
6604
6605         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6606         match events_4[0] {
6607                 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, .. } } => {
6608                         assert!(update_add_htlcs.is_empty());
6609                         assert!(update_fulfill_htlcs.is_empty());
6610                         assert_eq!(update_fail_htlcs.len(), 1);
6611                         assert!(update_fail_malformed_htlcs.is_empty());
6612                         assert!(update_fee.is_none());
6613                 },
6614                 _ => panic!("Unexpected event"),
6615         };
6616
6617         check_added_monitors!(nodes[1], 1);
6618 }
6619
6620 #[test]
6621 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6622         let chanmon_cfgs = create_chanmon_cfgs(3);
6623         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6624         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6625         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6626         create_announced_chan_between_nodes(&nodes, 0, 1);
6627         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6628
6629         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6630
6631         // First hop
6632         let mut payment_event = {
6633                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6634                 check_added_monitors!(nodes[0], 1);
6635                 SendEvent::from_node(&nodes[0])
6636         };
6637
6638         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6639         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6640         expect_pending_htlcs_forwardable!(nodes[1]);
6641         check_added_monitors!(nodes[1], 1);
6642         payment_event = SendEvent::from_node(&nodes[1]);
6643         assert_eq!(payment_event.msgs.len(), 1);
6644
6645         // Second Hop
6646         payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6647         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6648         check_added_monitors!(nodes[2], 0);
6649         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6650
6651         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6652         assert_eq!(events_3.len(), 1);
6653         match events_3[0] {
6654                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6655                         let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6656                         // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6657                         update_msg.failure_code |= 0x2000;
6658
6659                         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6660                         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6661                 },
6662                 _ => panic!("Unexpected event"),
6663         }
6664
6665         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6666                 vec![HTLCDestination::NextHopChannel {
6667                         node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6668         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6669         assert_eq!(events_4.len(), 1);
6670         check_added_monitors!(nodes[1], 1);
6671
6672         match events_4[0] {
6673                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6674                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6675                         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6676                 },
6677                 _ => panic!("Unexpected event"),
6678         }
6679
6680         let events_5 = nodes[0].node.get_and_clear_pending_events();
6681         assert_eq!(events_5.len(), 2);
6682
6683         // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6684         // the node originating the error to its next hop.
6685         match events_5[0] {
6686                 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6687                 } => {
6688                         assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6689                         assert!(is_permanent);
6690                         assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6691                 },
6692                 _ => panic!("Unexpected event"),
6693         }
6694         match events_5[1] {
6695                 Event::PaymentFailed { payment_hash, .. } => {
6696                         assert_eq!(payment_hash, our_payment_hash);
6697                 },
6698                 _ => panic!("Unexpected event"),
6699         }
6700
6701         // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6702 }
6703
6704 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6705         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6706         // 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
6707         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6708
6709         let mut chanmon_cfgs = create_chanmon_cfgs(2);
6710         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6711         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6712         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6713         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6714         let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
6715
6716         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6717                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6718
6719         // We route 2 dust-HTLCs between A and B
6720         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6721         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6722         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6723
6724         // Cache one local commitment tx as previous
6725         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6726
6727         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6728         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6729         check_added_monitors!(nodes[1], 0);
6730         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6731         check_added_monitors!(nodes[1], 1);
6732
6733         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6734         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6735         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6736         check_added_monitors!(nodes[0], 1);
6737
6738         // Cache one local commitment tx as lastest
6739         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6740
6741         let events = nodes[0].node.get_and_clear_pending_msg_events();
6742         match events[0] {
6743                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6744                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6745                 },
6746                 _ => panic!("Unexpected event"),
6747         }
6748         match events[1] {
6749                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6750                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6751                 },
6752                 _ => panic!("Unexpected event"),
6753         }
6754
6755         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6756         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6757         if announce_latest {
6758                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6759         } else {
6760                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6761         }
6762
6763         check_closed_broadcast!(nodes[0], true);
6764         check_added_monitors!(nodes[0], 1);
6765         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6766
6767         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6768         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6769         let events = nodes[0].node.get_and_clear_pending_events();
6770         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6771         assert_eq!(events.len(), 4);
6772         let mut first_failed = false;
6773         for event in events {
6774                 match event {
6775                         Event::PaymentPathFailed { payment_hash, .. } => {
6776                                 if payment_hash == payment_hash_1 {
6777                                         assert!(!first_failed);
6778                                         first_failed = true;
6779                                 } else {
6780                                         assert_eq!(payment_hash, payment_hash_2);
6781                                 }
6782                         },
6783                         Event::PaymentFailed { .. } => {}
6784                         _ => panic!("Unexpected event"),
6785                 }
6786         }
6787 }
6788
6789 #[test]
6790 fn test_failure_delay_dust_htlc_local_commitment() {
6791         do_test_failure_delay_dust_htlc_local_commitment(true);
6792         do_test_failure_delay_dust_htlc_local_commitment(false);
6793 }
6794
6795 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6796         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6797         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6798         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6799         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6800         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6801         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6802
6803         let chanmon_cfgs = create_chanmon_cfgs(3);
6804         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6805         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6806         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6807         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6808
6809         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6810                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6811
6812         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6813         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6814
6815         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6816         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6817
6818         // We revoked bs_commitment_tx
6819         if revoked {
6820                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6821                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6822         }
6823
6824         let mut timeout_tx = Vec::new();
6825         if local {
6826                 // We fail dust-HTLC 1 by broadcast of local commitment tx
6827                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
6828                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6829                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6830                 expect_payment_failed!(nodes[0], dust_hash, false);
6831
6832                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
6833                 check_closed_broadcast!(nodes[0], true);
6834                 check_added_monitors!(nodes[0], 1);
6835                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6836                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6837                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6838                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6839                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6840                 mine_transaction(&nodes[0], &timeout_tx[0]);
6841                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6842                 expect_payment_failed!(nodes[0], non_dust_hash, false);
6843         } else {
6844                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6845                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
6846                 check_closed_broadcast!(nodes[0], true);
6847                 check_added_monitors!(nodes[0], 1);
6848                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6849                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6850
6851                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
6852                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
6853                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
6854                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
6855                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
6856                 // dust HTLC should have been failed.
6857                 expect_payment_failed!(nodes[0], dust_hash, false);
6858
6859                 if !revoked {
6860                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6861                 } else {
6862                         assert_eq!(timeout_tx[0].lock_time.0, 0);
6863                 }
6864                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
6865                 mine_transaction(&nodes[0], &timeout_tx[0]);
6866                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6867                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6868                 expect_payment_failed!(nodes[0], non_dust_hash, false);
6869         }
6870 }
6871
6872 #[test]
6873 fn test_sweep_outbound_htlc_failure_update() {
6874         do_test_sweep_outbound_htlc_failure_update(false, true);
6875         do_test_sweep_outbound_htlc_failure_update(false, false);
6876         do_test_sweep_outbound_htlc_failure_update(true, false);
6877 }
6878
6879 #[test]
6880 fn test_user_configurable_csv_delay() {
6881         // We test our channel constructors yield errors when we pass them absurd csv delay
6882
6883         let mut low_our_to_self_config = UserConfig::default();
6884         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
6885         let mut high_their_to_self_config = UserConfig::default();
6886         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
6887         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6888         let chanmon_cfgs = create_chanmon_cfgs(2);
6889         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6890         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6891         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6892
6893         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6894         if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6895                 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
6896                 &low_our_to_self_config, 0, 42)
6897         {
6898                 match error {
6899                         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())); },
6900                         _ => panic!("Unexpected event"),
6901                 }
6902         } else { assert!(false) }
6903
6904         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6905         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6906         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6907         open_channel.to_self_delay = 200;
6908         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6909                 &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,
6910                 &low_our_to_self_config, 0, &nodes[0].logger, 42)
6911         {
6912                 match error {
6913                         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()));  },
6914                         _ => panic!("Unexpected event"),
6915                 }
6916         } else { assert!(false); }
6917
6918         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6919         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6920         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()));
6921         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6922         accept_channel.to_self_delay = 200;
6923         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
6924         let reason_msg;
6925         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
6926                 match action {
6927                         &ErrorAction::SendErrorMessage { ref msg } => {
6928                                 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()));
6929                                 reason_msg = msg.data.clone();
6930                         },
6931                         _ => { panic!(); }
6932                 }
6933         } else { panic!(); }
6934         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
6935
6936         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
6937         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6938         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6939         open_channel.to_self_delay = 200;
6940         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6941                 &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,
6942                 &high_their_to_self_config, 0, &nodes[0].logger, 42)
6943         {
6944                 match error {
6945                         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())); },
6946                         _ => panic!("Unexpected event"),
6947                 }
6948         } else { assert!(false); }
6949 }
6950
6951 #[test]
6952 fn test_check_htlc_underpaying() {
6953         // Send payment through A -> B but A is maliciously
6954         // sending a probe payment (i.e less than expected value0
6955         // to B, B should refuse payment.
6956
6957         let chanmon_cfgs = create_chanmon_cfgs(2);
6958         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6959         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6960         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6961
6962         // Create some initial channels
6963         create_announced_chan_between_nodes(&nodes, 0, 1);
6964
6965         let scorer = test_utils::TestScorer::new();
6966         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
6967         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV).with_features(nodes[1].node.invoice_features());
6968         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();
6969         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
6970         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
6971         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6972         check_added_monitors!(nodes[0], 1);
6973
6974         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6975         assert_eq!(events.len(), 1);
6976         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
6977         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6978         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6979
6980         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
6981         // and then will wait a second random delay before failing the HTLC back:
6982         expect_pending_htlcs_forwardable!(nodes[1]);
6983         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
6984
6985         // Node 3 is expecting payment of 100_000 but received 10_000,
6986         // it should fail htlc like we didn't know the preimage.
6987         nodes[1].node.process_pending_htlc_forwards();
6988
6989         let events = nodes[1].node.get_and_clear_pending_msg_events();
6990         assert_eq!(events.len(), 1);
6991         let (update_fail_htlc, commitment_signed) = match events[0] {
6992                 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 } } => {
6993                         assert!(update_add_htlcs.is_empty());
6994                         assert!(update_fulfill_htlcs.is_empty());
6995                         assert_eq!(update_fail_htlcs.len(), 1);
6996                         assert!(update_fail_malformed_htlcs.is_empty());
6997                         assert!(update_fee.is_none());
6998                         (update_fail_htlcs[0].clone(), commitment_signed)
6999                 },
7000                 _ => panic!("Unexpected event"),
7001         };
7002         check_added_monitors!(nodes[1], 1);
7003
7004         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7005         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7006
7007         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7008         let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7009         expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7010         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7011 }
7012
7013 #[test]
7014 fn test_announce_disable_channels() {
7015         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7016         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7017
7018         let chanmon_cfgs = create_chanmon_cfgs(2);
7019         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7020         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7021         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7022
7023         create_announced_chan_between_nodes(&nodes, 0, 1);
7024         create_announced_chan_between_nodes(&nodes, 1, 0);
7025         create_announced_chan_between_nodes(&nodes, 0, 1);
7026
7027         // Disconnect peers
7028         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7029         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7030
7031         nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7032         nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7033         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7034         assert_eq!(msg_events.len(), 3);
7035         let mut chans_disabled = HashMap::new();
7036         for e in msg_events {
7037                 match e {
7038                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7039                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7040                                 // Check that each channel gets updated exactly once
7041                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7042                                         panic!("Generated ChannelUpdate for wrong chan!");
7043                                 }
7044                         },
7045                         _ => panic!("Unexpected event"),
7046                 }
7047         }
7048         // Reconnect peers
7049         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();
7050         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7051         assert_eq!(reestablish_1.len(), 3);
7052         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();
7053         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7054         assert_eq!(reestablish_2.len(), 3);
7055
7056         // Reestablish chan_1
7057         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7058         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7059         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7060         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7061         // Reestablish chan_2
7062         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7063         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7064         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7065         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7066         // Reestablish chan_3
7067         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7068         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7069         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7070         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7071
7072         nodes[0].node.timer_tick_occurred();
7073         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7074         nodes[0].node.timer_tick_occurred();
7075         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7076         assert_eq!(msg_events.len(), 3);
7077         for e in msg_events {
7078                 match e {
7079                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7080                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7081                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7082                                         // Each update should have a higher timestamp than the previous one, replacing
7083                                         // the old one.
7084                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7085                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7086                                 }
7087                         },
7088                         _ => panic!("Unexpected event"),
7089                 }
7090         }
7091         // Check that each channel gets updated exactly once
7092         assert!(chans_disabled.is_empty());
7093 }
7094
7095 #[test]
7096 fn test_bump_penalty_txn_on_revoked_commitment() {
7097         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7098         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7099
7100         let chanmon_cfgs = create_chanmon_cfgs(2);
7101         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7102         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7103         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7104
7105         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7106
7107         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7108         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7109                 .with_features(nodes[0].node.invoice_features());
7110         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7111         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7112
7113         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7114         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7115         assert_eq!(revoked_txn[0].output.len(), 4);
7116         assert_eq!(revoked_txn[0].input.len(), 1);
7117         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7118         let revoked_txid = revoked_txn[0].txid();
7119
7120         let mut penalty_sum = 0;
7121         for outp in revoked_txn[0].output.iter() {
7122                 if outp.script_pubkey.is_v0_p2wsh() {
7123                         penalty_sum += outp.value;
7124                 }
7125         }
7126
7127         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7128         let header_114 = connect_blocks(&nodes[1], 14);
7129
7130         // Actually revoke tx by claiming a HTLC
7131         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7132         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7133         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7134         check_added_monitors!(nodes[1], 1);
7135
7136         // One or more justice tx should have been broadcast, check it
7137         let penalty_1;
7138         let feerate_1;
7139         {
7140                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7141                 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7142                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7143                 assert_eq!(node_txn[0].output.len(), 1);
7144                 check_spends!(node_txn[0], revoked_txn[0]);
7145                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7146                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7147                 penalty_1 = node_txn[0].txid();
7148                 node_txn.clear();
7149         };
7150
7151         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7152         connect_blocks(&nodes[1], 15);
7153         let mut penalty_2 = penalty_1;
7154         let mut feerate_2 = 0;
7155         {
7156                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7157                 assert_eq!(node_txn.len(), 1);
7158                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7159                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7160                         assert_eq!(node_txn[0].output.len(), 1);
7161                         check_spends!(node_txn[0], revoked_txn[0]);
7162                         penalty_2 = node_txn[0].txid();
7163                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7164                         assert_ne!(penalty_2, penalty_1);
7165                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7166                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7167                         // Verify 25% bump heuristic
7168                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7169                         node_txn.clear();
7170                 }
7171         }
7172         assert_ne!(feerate_2, 0);
7173
7174         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7175         connect_blocks(&nodes[1], 1);
7176         let penalty_3;
7177         let mut feerate_3 = 0;
7178         {
7179                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7180                 assert_eq!(node_txn.len(), 1);
7181                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7182                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7183                         assert_eq!(node_txn[0].output.len(), 1);
7184                         check_spends!(node_txn[0], revoked_txn[0]);
7185                         penalty_3 = node_txn[0].txid();
7186                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7187                         assert_ne!(penalty_3, penalty_2);
7188                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7189                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7190                         // Verify 25% bump heuristic
7191                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7192                         node_txn.clear();
7193                 }
7194         }
7195         assert_ne!(feerate_3, 0);
7196
7197         nodes[1].node.get_and_clear_pending_events();
7198         nodes[1].node.get_and_clear_pending_msg_events();
7199 }
7200
7201 #[test]
7202 fn test_bump_penalty_txn_on_revoked_htlcs() {
7203         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7204         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7205
7206         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7207         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7208         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7209         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7210         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7211
7212         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7213         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7214         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_features(nodes[1].node.invoice_features());
7215         let scorer = test_utils::TestScorer::new();
7216         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7217         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7218                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7219         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7220         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_features(nodes[0].node.invoice_features());
7221         let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7222                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7223         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7224
7225         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7226         assert_eq!(revoked_local_txn[0].input.len(), 1);
7227         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7228
7229         // Revoke local commitment tx
7230         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7231
7232         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7233         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7234         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7235         check_closed_broadcast!(nodes[1], true);
7236         check_added_monitors!(nodes[1], 1);
7237         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7238         connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7239
7240         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
7241         assert_eq!(revoked_htlc_txn.len(), 2);
7242
7243         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7244         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7245         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7246
7247         assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7248         assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7249         assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7250         check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7251
7252         // Broadcast set of revoked txn on A
7253         let hash_128 = connect_blocks(&nodes[0], 40);
7254         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7255         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7256         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7257         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] });
7258         let events = nodes[0].node.get_and_clear_pending_events();
7259         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7260         match events.last().unwrap() {
7261                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7262                 _ => panic!("Unexpected event"),
7263         }
7264         let first;
7265         let feerate_1;
7266         let penalty_txn;
7267         {
7268                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7269                 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7270                 // Verify claim tx are spending revoked HTLC txn
7271
7272                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7273                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7274                 // which are included in the same block (they are broadcasted because we scan the
7275                 // transactions linearly and generate claims as we go, they likely should be removed in the
7276                 // future).
7277                 assert_eq!(node_txn[0].input.len(), 1);
7278                 check_spends!(node_txn[0], revoked_local_txn[0]);
7279                 assert_eq!(node_txn[1].input.len(), 1);
7280                 check_spends!(node_txn[1], revoked_local_txn[0]);
7281                 assert_eq!(node_txn[2].input.len(), 1);
7282                 check_spends!(node_txn[2], revoked_local_txn[0]);
7283
7284                 // Each of the three justice transactions claim a separate (single) output of the three
7285                 // available, which we check here:
7286                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7287                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7288                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7289
7290                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7291                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7292
7293                 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7294                 // output, checked above).
7295                 assert_eq!(node_txn[3].input.len(), 2);
7296                 assert_eq!(node_txn[3].output.len(), 1);
7297                 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7298
7299                 first = node_txn[3].txid();
7300                 // Store both feerates for later comparison
7301                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7302                 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7303                 penalty_txn = vec![node_txn[2].clone()];
7304                 node_txn.clear();
7305         }
7306
7307         // Connect one more block to see if bumped penalty are issued for HTLC txn
7308         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7309         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7310         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7311         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7312
7313         // Few more blocks to confirm penalty txn
7314         connect_blocks(&nodes[0], 4);
7315         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7316         let header_144 = connect_blocks(&nodes[0], 9);
7317         let node_txn = {
7318                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7319                 assert_eq!(node_txn.len(), 1);
7320
7321                 assert_eq!(node_txn[0].input.len(), 2);
7322                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7323                 // Verify bumped tx is different and 25% bump heuristic
7324                 assert_ne!(first, node_txn[0].txid());
7325                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7326                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7327                 assert!(feerate_2 * 100 > feerate_1 * 125);
7328                 let txn = vec![node_txn[0].clone()];
7329                 node_txn.clear();
7330                 txn
7331         };
7332         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7333         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7334         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7335         connect_blocks(&nodes[0], 20);
7336         {
7337                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7338                 // We verify than no new transaction has been broadcast because previously
7339                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7340                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7341                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7342                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7343                 // up bumped justice generation.
7344                 assert_eq!(node_txn.len(), 0);
7345                 node_txn.clear();
7346         }
7347         check_closed_broadcast!(nodes[0], true);
7348         check_added_monitors!(nodes[0], 1);
7349 }
7350
7351 #[test]
7352 fn test_bump_penalty_txn_on_remote_commitment() {
7353         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7354         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7355
7356         // Create 2 HTLCs
7357         // Provide preimage for one
7358         // Check aggregation
7359
7360         let chanmon_cfgs = create_chanmon_cfgs(2);
7361         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7362         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7363         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7364
7365         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7366         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7367         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7368
7369         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7370         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7371         assert_eq!(remote_txn[0].output.len(), 4);
7372         assert_eq!(remote_txn[0].input.len(), 1);
7373         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7374
7375         // Claim a HTLC without revocation (provide B monitor with preimage)
7376         nodes[1].node.claim_funds(payment_preimage);
7377         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7378         mine_transaction(&nodes[1], &remote_txn[0]);
7379         check_added_monitors!(nodes[1], 2);
7380         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7381
7382         // One or more claim tx should have been broadcast, check it
7383         let timeout;
7384         let preimage;
7385         let preimage_bump;
7386         let feerate_timeout;
7387         let feerate_preimage;
7388         {
7389                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7390                 // 3 transactions including:
7391                 //   preimage and timeout sweeps from remote commitment + preimage sweep bump
7392                 assert_eq!(node_txn.len(), 3);
7393                 assert_eq!(node_txn[0].input.len(), 1);
7394                 assert_eq!(node_txn[1].input.len(), 1);
7395                 assert_eq!(node_txn[2].input.len(), 1);
7396                 check_spends!(node_txn[0], remote_txn[0]);
7397                 check_spends!(node_txn[1], remote_txn[0]);
7398                 check_spends!(node_txn[2], remote_txn[0]);
7399
7400                 preimage = node_txn[0].txid();
7401                 let index = node_txn[0].input[0].previous_output.vout;
7402                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7403                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7404
7405                 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7406                         (node_txn[2].clone(), node_txn[1].clone())
7407                 } else {
7408                         (node_txn[1].clone(), node_txn[2].clone())
7409                 };
7410
7411                 preimage_bump = preimage_bump_tx;
7412                 check_spends!(preimage_bump, remote_txn[0]);
7413                 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7414
7415                 timeout = timeout_tx.txid();
7416                 let index = timeout_tx.input[0].previous_output.vout;
7417                 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7418                 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7419
7420                 node_txn.clear();
7421         };
7422         assert_ne!(feerate_timeout, 0);
7423         assert_ne!(feerate_preimage, 0);
7424
7425         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7426         connect_blocks(&nodes[1], 15);
7427         {
7428                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7429                 assert_eq!(node_txn.len(), 1);
7430                 assert_eq!(node_txn[0].input.len(), 1);
7431                 assert_eq!(preimage_bump.input.len(), 1);
7432                 check_spends!(node_txn[0], remote_txn[0]);
7433                 check_spends!(preimage_bump, remote_txn[0]);
7434
7435                 let index = preimage_bump.input[0].previous_output.vout;
7436                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7437                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7438                 assert!(new_feerate * 100 > feerate_timeout * 125);
7439                 assert_ne!(timeout, preimage_bump.txid());
7440
7441                 let index = node_txn[0].input[0].previous_output.vout;
7442                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7443                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7444                 assert!(new_feerate * 100 > feerate_preimage * 125);
7445                 assert_ne!(preimage, node_txn[0].txid());
7446
7447                 node_txn.clear();
7448         }
7449
7450         nodes[1].node.get_and_clear_pending_events();
7451         nodes[1].node.get_and_clear_pending_msg_events();
7452 }
7453
7454 #[test]
7455 fn test_counterparty_raa_skip_no_crash() {
7456         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7457         // commitment transaction, we would have happily carried on and provided them the next
7458         // commitment transaction based on one RAA forward. This would probably eventually have led to
7459         // channel closure, but it would not have resulted in funds loss. Still, our
7460         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7461         // check simply that the channel is closed in response to such an RAA, but don't check whether
7462         // we decide to punish our counterparty for revoking their funds (as we don't currently
7463         // implement that).
7464         let chanmon_cfgs = create_chanmon_cfgs(2);
7465         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7466         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7467         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7468         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7469
7470         let per_commitment_secret;
7471         let next_per_commitment_point;
7472         {
7473                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7474                 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7475                 let keys = guard.channel_by_id.get_mut(&channel_id).unwrap().get_signer();
7476
7477                 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7478
7479                 // Make signer believe we got a counterparty signature, so that it allows the revocation
7480                 keys.get_enforcement_state().last_holder_commitment -= 1;
7481                 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7482
7483                 // Must revoke without gaps
7484                 keys.get_enforcement_state().last_holder_commitment -= 1;
7485                 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7486
7487                 keys.get_enforcement_state().last_holder_commitment -= 1;
7488                 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7489                         &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7490         }
7491
7492         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7493                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7494         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7495         check_added_monitors!(nodes[1], 1);
7496         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7497 }
7498
7499 #[test]
7500 fn test_bump_txn_sanitize_tracking_maps() {
7501         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7502         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7503
7504         let chanmon_cfgs = create_chanmon_cfgs(2);
7505         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7506         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7507         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7508
7509         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7510         // Lock HTLC in both directions
7511         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7512         let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7513
7514         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7515         assert_eq!(revoked_local_txn[0].input.len(), 1);
7516         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7517
7518         // Revoke local commitment tx
7519         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7520
7521         // Broadcast set of revoked txn on A
7522         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7523         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7524         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7525
7526         mine_transaction(&nodes[0], &revoked_local_txn[0]);
7527         check_closed_broadcast!(nodes[0], true);
7528         check_added_monitors!(nodes[0], 1);
7529         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7530         let penalty_txn = {
7531                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7532                 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7533                 check_spends!(node_txn[0], revoked_local_txn[0]);
7534                 check_spends!(node_txn[1], revoked_local_txn[0]);
7535                 check_spends!(node_txn[2], revoked_local_txn[0]);
7536                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7537                 node_txn.clear();
7538                 penalty_txn
7539         };
7540         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7541         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7542         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7543         {
7544                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7545                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7546                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7547         }
7548 }
7549
7550 #[test]
7551 fn test_pending_claimed_htlc_no_balance_underflow() {
7552         // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
7553         // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
7554         let chanmon_cfgs = create_chanmon_cfgs(2);
7555         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7556         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7557         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7558         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
7559
7560         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
7561         nodes[1].node.claim_funds(payment_preimage);
7562         expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
7563         check_added_monitors!(nodes[1], 1);
7564         let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7565
7566         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
7567         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
7568         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
7569         check_added_monitors!(nodes[0], 1);
7570         let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7571
7572         // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
7573         // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
7574         // can get our balance.
7575
7576         // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
7577         // the public key of the only hop. This works around ChannelDetails not showing the
7578         // almost-claimed HTLC as available balance.
7579         let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
7580         route.payment_params = None; // This is all wrong, but unnecessary
7581         route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
7582         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
7583         nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
7584
7585         assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
7586 }
7587
7588 #[test]
7589 fn test_channel_conf_timeout() {
7590         // Tests that, for inbound channels, we give up on them if the funding transaction does not
7591         // confirm within 2016 blocks, as recommended by BOLT 2.
7592         let chanmon_cfgs = create_chanmon_cfgs(2);
7593         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7594         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7595         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7596
7597         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7598
7599         // The outbound node should wait forever for confirmation:
7600         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7601         // copied here instead of directly referencing the constant.
7602         connect_blocks(&nodes[0], 2016);
7603         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7604
7605         // The inbound node should fail the channel after exactly 2016 blocks
7606         connect_blocks(&nodes[1], 2015);
7607         check_added_monitors!(nodes[1], 0);
7608         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7609
7610         connect_blocks(&nodes[1], 1);
7611         check_added_monitors!(nodes[1], 1);
7612         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
7613         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7614         assert_eq!(close_ev.len(), 1);
7615         match close_ev[0] {
7616                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7617                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7618                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7619                 },
7620                 _ => panic!("Unexpected event"),
7621         }
7622 }
7623
7624 #[test]
7625 fn test_override_channel_config() {
7626         let chanmon_cfgs = create_chanmon_cfgs(2);
7627         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7628         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7629         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7630
7631         // Node0 initiates a channel to node1 using the override config.
7632         let mut override_config = UserConfig::default();
7633         override_config.channel_handshake_config.our_to_self_delay = 200;
7634
7635         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7636
7637         // Assert the channel created by node0 is using the override config.
7638         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7639         assert_eq!(res.channel_flags, 0);
7640         assert_eq!(res.to_self_delay, 200);
7641 }
7642
7643 #[test]
7644 fn test_override_0msat_htlc_minimum() {
7645         let mut zero_config = UserConfig::default();
7646         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7647         let chanmon_cfgs = create_chanmon_cfgs(2);
7648         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7649         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7650         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7651
7652         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7653         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7654         assert_eq!(res.htlc_minimum_msat, 1);
7655
7656         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7657         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7658         assert_eq!(res.htlc_minimum_msat, 1);
7659 }
7660
7661 #[test]
7662 fn test_channel_update_has_correct_htlc_maximum_msat() {
7663         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7664         // Bolt 7 specifies that if present `htlc_maximum_msat`:
7665         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7666         // 90% of the `channel_value`.
7667         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7668
7669         let mut config_30_percent = UserConfig::default();
7670         config_30_percent.channel_handshake_config.announced_channel = true;
7671         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7672         let mut config_50_percent = UserConfig::default();
7673         config_50_percent.channel_handshake_config.announced_channel = true;
7674         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7675         let mut config_95_percent = UserConfig::default();
7676         config_95_percent.channel_handshake_config.announced_channel = true;
7677         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7678         let mut config_100_percent = UserConfig::default();
7679         config_100_percent.channel_handshake_config.announced_channel = true;
7680         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7681
7682         let chanmon_cfgs = create_chanmon_cfgs(4);
7683         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7684         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)]);
7685         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7686
7687         let channel_value_satoshis = 100000;
7688         let channel_value_msat = channel_value_satoshis * 1000;
7689         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7690         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7691         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7692
7693         let (node_0_chan_update, node_1_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7694         let (node_2_chan_update, node_3_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7695
7696         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7697         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7698         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7699         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7700         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7701         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7702
7703         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7704         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7705         // `channel_value`.
7706         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7707         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7708         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7709         // `channel_value`.
7710         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7711 }
7712
7713 #[test]
7714 fn test_manually_accept_inbound_channel_request() {
7715         let mut manually_accept_conf = UserConfig::default();
7716         manually_accept_conf.manually_accept_inbound_channels = true;
7717         let chanmon_cfgs = create_chanmon_cfgs(2);
7718         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7719         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7720         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7721
7722         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7723         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7724
7725         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7726
7727         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7728         // accepting the inbound channel request.
7729         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7730
7731         let events = nodes[1].node.get_and_clear_pending_events();
7732         match events[0] {
7733                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7734                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7735                 }
7736                 _ => panic!("Unexpected event"),
7737         }
7738
7739         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7740         assert_eq!(accept_msg_ev.len(), 1);
7741
7742         match accept_msg_ev[0] {
7743                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7744                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7745                 }
7746                 _ => panic!("Unexpected event"),
7747         }
7748
7749         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7750
7751         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7752         assert_eq!(close_msg_ev.len(), 1);
7753
7754         let events = nodes[1].node.get_and_clear_pending_events();
7755         match events[0] {
7756                 Event::ChannelClosed { user_channel_id, .. } => {
7757                         assert_eq!(user_channel_id, 23);
7758                 }
7759                 _ => panic!("Unexpected event"),
7760         }
7761 }
7762
7763 #[test]
7764 fn test_manually_reject_inbound_channel_request() {
7765         let mut manually_accept_conf = UserConfig::default();
7766         manually_accept_conf.manually_accept_inbound_channels = true;
7767         let chanmon_cfgs = create_chanmon_cfgs(2);
7768         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7769         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7770         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7771
7772         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7773         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7774
7775         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7776
7777         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7778         // rejecting the inbound channel request.
7779         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7780
7781         let events = nodes[1].node.get_and_clear_pending_events();
7782         match events[0] {
7783                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7784                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7785                 }
7786                 _ => panic!("Unexpected event"),
7787         }
7788
7789         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7790         assert_eq!(close_msg_ev.len(), 1);
7791
7792         match close_msg_ev[0] {
7793                 MessageSendEvent::HandleError { ref node_id, .. } => {
7794                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7795                 }
7796                 _ => panic!("Unexpected event"),
7797         }
7798         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
7799 }
7800
7801 #[test]
7802 fn test_reject_funding_before_inbound_channel_accepted() {
7803         // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
7804         // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
7805         // the node operator before the counterparty sends a `FundingCreated` message. If a
7806         // `FundingCreated` message is received before the channel is accepted, it should be rejected
7807         // and the channel should be closed.
7808         let mut manually_accept_conf = UserConfig::default();
7809         manually_accept_conf.manually_accept_inbound_channels = true;
7810         let chanmon_cfgs = create_chanmon_cfgs(2);
7811         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7812         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7813         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7814
7815         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7816         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7817         let temp_channel_id = res.temporary_channel_id;
7818
7819         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7820
7821         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
7822         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7823
7824         // Clear the `Event::OpenChannelRequest` event without responding to the request.
7825         nodes[1].node.get_and_clear_pending_events();
7826
7827         // Get the `AcceptChannel` message of `nodes[1]` without calling
7828         // `ChannelManager::accept_inbound_channel`, which generates a
7829         // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
7830         // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
7831         // succeed when `nodes[0]` is passed to it.
7832         let accept_chan_msg = {
7833                 let mut node_1_per_peer_lock;
7834                 let mut node_1_peer_state_lock;
7835                 let channel =  get_channel_ref!(&nodes[1], nodes[0], node_1_per_peer_lock, node_1_peer_state_lock, temp_channel_id);
7836                 channel.get_accept_channel_message()
7837         };
7838         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
7839
7840         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
7841
7842         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
7843         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
7844
7845         // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
7846         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
7847
7848         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7849         assert_eq!(close_msg_ev.len(), 1);
7850
7851         let expected_err = "FundingCreated message received before the channel was accepted";
7852         match close_msg_ev[0] {
7853                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
7854                         assert_eq!(msg.channel_id, temp_channel_id);
7855                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7856                         assert_eq!(msg.data, expected_err);
7857                 }
7858                 _ => panic!("Unexpected event"),
7859         }
7860
7861         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
7862 }
7863
7864 #[test]
7865 fn test_can_not_accept_inbound_channel_twice() {
7866         let mut manually_accept_conf = UserConfig::default();
7867         manually_accept_conf.manually_accept_inbound_channels = true;
7868         let chanmon_cfgs = create_chanmon_cfgs(2);
7869         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7870         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7871         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7872
7873         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7874         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7875
7876         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7877
7878         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7879         // accepting the inbound channel request.
7880         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7881
7882         let events = nodes[1].node.get_and_clear_pending_events();
7883         match events[0] {
7884                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7885                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7886                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7887                         match api_res {
7888                                 Err(APIError::APIMisuseError { err }) => {
7889                                         assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
7890                                 },
7891                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7892                                 Err(_) => panic!("Unexpected Error"),
7893                         }
7894                 }
7895                 _ => panic!("Unexpected event"),
7896         }
7897
7898         // Ensure that the channel wasn't closed after attempting to accept it twice.
7899         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7900         assert_eq!(accept_msg_ev.len(), 1);
7901
7902         match accept_msg_ev[0] {
7903                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7904                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7905                 }
7906                 _ => panic!("Unexpected event"),
7907         }
7908 }
7909
7910 #[test]
7911 fn test_can_not_accept_unknown_inbound_channel() {
7912         let chanmon_cfg = create_chanmon_cfgs(2);
7913         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
7914         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
7915         let nodes = create_network(2, &node_cfg, &node_chanmgr);
7916
7917         let unknown_channel_id = [0; 32];
7918         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
7919         match api_res {
7920                 Err(APIError::ChannelUnavailable { err }) => {
7921                         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()));
7922                 },
7923                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
7924                 Err(_) => panic!("Unexpected Error"),
7925         }
7926 }
7927
7928 #[test]
7929 fn test_simple_mpp() {
7930         // Simple test of sending a multi-path payment.
7931         let chanmon_cfgs = create_chanmon_cfgs(4);
7932         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7933         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
7934         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7935
7936         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
7937         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
7938         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
7939         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
7940
7941         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
7942         let path = route.paths[0].clone();
7943         route.paths.push(path);
7944         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
7945         route.paths[0][0].short_channel_id = chan_1_id;
7946         route.paths[0][1].short_channel_id = chan_3_id;
7947         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
7948         route.paths[1][0].short_channel_id = chan_2_id;
7949         route.paths[1][1].short_channel_id = chan_4_id;
7950         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
7951         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
7952 }
7953
7954 #[test]
7955 fn test_preimage_storage() {
7956         // Simple test of payment preimage storage allowing no client-side storage to claim payments
7957         let chanmon_cfgs = create_chanmon_cfgs(2);
7958         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7959         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7960         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7961
7962         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
7963
7964         {
7965                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
7966                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
7967                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
7968                 check_added_monitors!(nodes[0], 1);
7969                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7970                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7971                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7972                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7973         }
7974         // Note that after leaving the above scope we have no knowledge of any arguments or return
7975         // values from previous calls.
7976         expect_pending_htlcs_forwardable!(nodes[1]);
7977         let events = nodes[1].node.get_and_clear_pending_events();
7978         assert_eq!(events.len(), 1);
7979         match events[0] {
7980                 Event::PaymentClaimable { ref purpose, .. } => {
7981                         match &purpose {
7982                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
7983                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
7984                                 },
7985                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
7986                         }
7987                 },
7988                 _ => panic!("Unexpected event"),
7989         }
7990 }
7991
7992 #[test]
7993 #[allow(deprecated)]
7994 fn test_secret_timeout() {
7995         // Simple test of payment secret storage time outs. After
7996         // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
7997         let chanmon_cfgs = create_chanmon_cfgs(2);
7998         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7999         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8000         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8001
8002         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8003
8004         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8005
8006         // We should fail to register the same payment hash twice, at least until we've connected a
8007         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8008         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8009                 assert_eq!(err, "Duplicate payment hash");
8010         } else { panic!(); }
8011         let mut block = {
8012                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8013                 Block {
8014                         header: BlockHeader {
8015                                 version: 0x2000000,
8016                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8017                                 merkle_root: TxMerkleNode::all_zeros(),
8018                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8019                         txdata: vec![],
8020                 }
8021         };
8022         connect_block(&nodes[1], &block);
8023         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8024                 assert_eq!(err, "Duplicate payment hash");
8025         } else { panic!(); }
8026
8027         // If we then connect the second block, we should be able to register the same payment hash
8028         // again (this time getting a new payment secret).
8029         block.header.prev_blockhash = block.header.block_hash();
8030         block.header.time += 1;
8031         connect_block(&nodes[1], &block);
8032         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8033         assert_ne!(payment_secret_1, our_payment_secret);
8034
8035         {
8036                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8037                 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret), PaymentId(payment_hash.0)).unwrap();
8038                 check_added_monitors!(nodes[0], 1);
8039                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8040                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8041                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8042                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8043         }
8044         // Note that after leaving the above scope we have no knowledge of any arguments or return
8045         // values from previous calls.
8046         expect_pending_htlcs_forwardable!(nodes[1]);
8047         let events = nodes[1].node.get_and_clear_pending_events();
8048         assert_eq!(events.len(), 1);
8049         match events[0] {
8050                 Event::PaymentClaimable { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8051                         assert!(payment_preimage.is_none());
8052                         assert_eq!(payment_secret, our_payment_secret);
8053                         // We don't actually have the payment preimage with which to claim this payment!
8054                 },
8055                 _ => panic!("Unexpected event"),
8056         }
8057 }
8058
8059 #[test]
8060 fn test_bad_secret_hash() {
8061         // Simple test of unregistered payment hash/invalid payment secret handling
8062         let chanmon_cfgs = create_chanmon_cfgs(2);
8063         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8064         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8065         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8066
8067         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8068
8069         let random_payment_hash = PaymentHash([42; 32]);
8070         let random_payment_secret = PaymentSecret([43; 32]);
8071         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8072         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8073
8074         // All the below cases should end up being handled exactly identically, so we macro the
8075         // resulting events.
8076         macro_rules! handle_unknown_invalid_payment_data {
8077                 ($payment_hash: expr) => {
8078                         check_added_monitors!(nodes[0], 1);
8079                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8080                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8081                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8082                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8083
8084                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8085                         // again to process the pending backwards-failure of the HTLC
8086                         expect_pending_htlcs_forwardable!(nodes[1]);
8087                         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8088                         check_added_monitors!(nodes[1], 1);
8089
8090                         // We should fail the payment back
8091                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8092                         match events.pop().unwrap() {
8093                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8094                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8095                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8096                                 },
8097                                 _ => panic!("Unexpected event"),
8098                         }
8099                 }
8100         }
8101
8102         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8103         // Error data is the HTLC value (100,000) and current block height
8104         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8105
8106         // Send a payment with the right payment hash but the wrong payment secret
8107         nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8108         handle_unknown_invalid_payment_data!(our_payment_hash);
8109         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8110
8111         // Send a payment with a random payment hash, but the right payment secret
8112         nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8113         handle_unknown_invalid_payment_data!(random_payment_hash);
8114         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8115
8116         // Send a payment with a random payment hash and random payment secret
8117         nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8118         handle_unknown_invalid_payment_data!(random_payment_hash);
8119         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8120 }
8121
8122 #[test]
8123 fn test_update_err_monitor_lockdown() {
8124         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8125         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8126         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8127         // error.
8128         //
8129         // This scenario may happen in a watchtower setup, where watchtower process a block height
8130         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8131         // commitment at same time.
8132
8133         let chanmon_cfgs = create_chanmon_cfgs(2);
8134         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8135         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8136         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8137
8138         // Create some initial channel
8139         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8140         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8141
8142         // Rebalance the network to generate htlc in the two directions
8143         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8144
8145         // Route a HTLC from node 0 to node 1 (but don't settle)
8146         let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8147
8148         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8149         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8150         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8151         let persister = test_utils::TestPersister::new();
8152         let watchtower = {
8153                 let new_monitor = {
8154                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8155                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8156                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8157                         assert!(new_monitor == *monitor);
8158                         new_monitor
8159                 };
8160                 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);
8161                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8162                 watchtower
8163         };
8164         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8165         let block = Block { header, txdata: vec![] };
8166         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8167         // transaction lock time requirements here.
8168         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8169         watchtower.chain_monitor.block_connected(&block, 200);
8170
8171         // Try to update ChannelMonitor
8172         nodes[1].node.claim_funds(preimage);
8173         check_added_monitors!(nodes[1], 1);
8174         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8175
8176         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8177         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8178         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8179         {
8180                 let mut node_0_per_peer_lock;
8181                 let mut node_0_peer_state_lock;
8182                 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8183                 if let Ok(update) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8184                         assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8185                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8186                 } else { assert!(false); }
8187         }
8188         // Our local monitor is in-sync and hasn't processed yet timeout
8189         check_added_monitors!(nodes[0], 1);
8190         let events = nodes[0].node.get_and_clear_pending_events();
8191         assert_eq!(events.len(), 1);
8192 }
8193
8194 #[test]
8195 fn test_concurrent_monitor_claim() {
8196         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8197         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8198         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8199         // state N+1 confirms. Alice claims output from state N+1.
8200
8201         let chanmon_cfgs = create_chanmon_cfgs(2);
8202         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8203         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8204         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8205
8206         // Create some initial channel
8207         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8208         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8209
8210         // Rebalance the network to generate htlc in the two directions
8211         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8212
8213         // Route a HTLC from node 0 to node 1 (but don't settle)
8214         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8215
8216         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8217         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8218         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8219         let persister = test_utils::TestPersister::new();
8220         let watchtower_alice = {
8221                 let new_monitor = {
8222                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8223                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8224                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8225                         assert!(new_monitor == *monitor);
8226                         new_monitor
8227                 };
8228                 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);
8229                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8230                 watchtower
8231         };
8232         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8233         let block = Block { header, txdata: vec![] };
8234         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8235         // transaction lock time requirements here.
8236         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));
8237         watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8238
8239         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8240         {
8241                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8242                 assert_eq!(txn.len(), 2);
8243                 txn.clear();
8244         }
8245
8246         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8247         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8248         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8249         let persister = test_utils::TestPersister::new();
8250         let watchtower_bob = {
8251                 let new_monitor = {
8252                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8253                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8254                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8255                         assert!(new_monitor == *monitor);
8256                         new_monitor
8257                 };
8258                 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);
8259                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8260                 watchtower
8261         };
8262         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8263         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8264
8265         // Route another payment to generate another update with still previous HTLC pending
8266         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8267         {
8268                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
8269         }
8270         check_added_monitors!(nodes[1], 1);
8271
8272         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8273         assert_eq!(updates.update_add_htlcs.len(), 1);
8274         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8275         {
8276                 let mut node_0_per_peer_lock;
8277                 let mut node_0_peer_state_lock;
8278                 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8279                 if let Ok(update) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8280                         // Watchtower Alice should already have seen the block and reject the update
8281                         assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8282                         assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8283                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8284                 } else { assert!(false); }
8285         }
8286         // Our local monitor is in-sync and hasn't processed yet timeout
8287         check_added_monitors!(nodes[0], 1);
8288
8289         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8290         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8291         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8292
8293         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8294         let bob_state_y;
8295         {
8296                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8297                 assert_eq!(txn.len(), 2);
8298                 bob_state_y = txn[0].clone();
8299                 txn.clear();
8300         };
8301
8302         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8303         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8304         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);
8305         {
8306                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8307                 assert_eq!(htlc_txn.len(), 1);
8308                 check_spends!(htlc_txn[0], bob_state_y);
8309         }
8310 }
8311
8312 #[test]
8313 fn test_pre_lockin_no_chan_closed_update() {
8314         // Test that if a peer closes a channel in response to a funding_created message we don't
8315         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8316         // message).
8317         //
8318         // Doing so would imply a channel monitor update before the initial channel monitor
8319         // registration, violating our API guarantees.
8320         //
8321         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8322         // then opening a second channel with the same funding output as the first (which is not
8323         // rejected because the first channel does not exist in the ChannelManager) and closing it
8324         // before receiving funding_signed.
8325         let chanmon_cfgs = create_chanmon_cfgs(2);
8326         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8327         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8328         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8329
8330         // Create an initial channel
8331         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8332         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8333         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8334         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8335         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8336
8337         // Move the first channel through the funding flow...
8338         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8339
8340         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8341         check_added_monitors!(nodes[0], 0);
8342
8343         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8344         let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8345         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8346         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8347         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8348 }
8349
8350 #[test]
8351 fn test_htlc_no_detection() {
8352         // This test is a mutation to underscore the detection logic bug we had
8353         // before #653. HTLC value routed is above the remaining balance, thus
8354         // inverting HTLC and `to_remote` output. HTLC will come second and
8355         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8356         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8357         // outputs order detection for correct spending children filtring.
8358
8359         let chanmon_cfgs = create_chanmon_cfgs(2);
8360         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8361         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8362         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8363
8364         // Create some initial channels
8365         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8366
8367         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8368         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8369         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8370         assert_eq!(local_txn[0].input.len(), 1);
8371         assert_eq!(local_txn[0].output.len(), 3);
8372         check_spends!(local_txn[0], chan_1.3);
8373
8374         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8375         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8376         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8377         // We deliberately connect the local tx twice as this should provoke a failure calling
8378         // this test before #653 fix.
8379         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);
8380         check_closed_broadcast!(nodes[0], true);
8381         check_added_monitors!(nodes[0], 1);
8382         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8383         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8384
8385         let htlc_timeout = {
8386                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8387                 assert_eq!(node_txn.len(), 1);
8388                 assert_eq!(node_txn[0].input.len(), 1);
8389                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8390                 check_spends!(node_txn[0], local_txn[0]);
8391                 node_txn[0].clone()
8392         };
8393
8394         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8395         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8396         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8397         expect_payment_failed!(nodes[0], our_payment_hash, false);
8398 }
8399
8400 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8401         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8402         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8403         // Carol, Alice would be the upstream node, and Carol the downstream.)
8404         //
8405         // Steps of the test:
8406         // 1) Alice sends a HTLC to Carol through Bob.
8407         // 2) Carol doesn't settle the HTLC.
8408         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8409         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8410         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8411         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8412         // 5) Carol release the preimage to Bob off-chain.
8413         // 6) Bob claims the offered output on the broadcasted commitment.
8414         let chanmon_cfgs = create_chanmon_cfgs(3);
8415         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8416         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8417         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8418
8419         // Create some initial channels
8420         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8421         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8422
8423         // Steps (1) and (2):
8424         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8425         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8426
8427         // Check that Alice's commitment transaction now contains an output for this HTLC.
8428         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8429         check_spends!(alice_txn[0], chan_ab.3);
8430         assert_eq!(alice_txn[0].output.len(), 2);
8431         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8432         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8433         assert_eq!(alice_txn.len(), 2);
8434
8435         // Steps (3) and (4):
8436         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8437         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8438         let mut force_closing_node = 0; // Alice force-closes
8439         let mut counterparty_node = 1; // Bob if Alice force-closes
8440
8441         // Bob force-closes
8442         if !broadcast_alice {
8443                 force_closing_node = 1;
8444                 counterparty_node = 0;
8445         }
8446         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8447         check_closed_broadcast!(nodes[force_closing_node], true);
8448         check_added_monitors!(nodes[force_closing_node], 1);
8449         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8450         if go_onchain_before_fulfill {
8451                 let txn_to_broadcast = match broadcast_alice {
8452                         true => alice_txn.clone(),
8453                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8454                 };
8455                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8456                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8457                 if broadcast_alice {
8458                         check_closed_broadcast!(nodes[1], true);
8459                         check_added_monitors!(nodes[1], 1);
8460                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8461                 }
8462         }
8463
8464         // Step (5):
8465         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8466         // process of removing the HTLC from their commitment transactions.
8467         nodes[2].node.claim_funds(payment_preimage);
8468         check_added_monitors!(nodes[2], 1);
8469         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8470
8471         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8472         assert!(carol_updates.update_add_htlcs.is_empty());
8473         assert!(carol_updates.update_fail_htlcs.is_empty());
8474         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8475         assert!(carol_updates.update_fee.is_none());
8476         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8477
8478         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8479         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8480         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8481         if !go_onchain_before_fulfill && broadcast_alice {
8482                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8483                 assert_eq!(events.len(), 1);
8484                 match events[0] {
8485                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8486                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8487                         },
8488                         _ => panic!("Unexpected event"),
8489                 };
8490         }
8491         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8492         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8493         // Carol<->Bob's updated commitment transaction info.
8494         check_added_monitors!(nodes[1], 2);
8495
8496         let events = nodes[1].node.get_and_clear_pending_msg_events();
8497         assert_eq!(events.len(), 2);
8498         let bob_revocation = match events[0] {
8499                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8500                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8501                         (*msg).clone()
8502                 },
8503                 _ => panic!("Unexpected event"),
8504         };
8505         let bob_updates = match events[1] {
8506                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8507                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8508                         (*updates).clone()
8509                 },
8510                 _ => panic!("Unexpected event"),
8511         };
8512
8513         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8514         check_added_monitors!(nodes[2], 1);
8515         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8516         check_added_monitors!(nodes[2], 1);
8517
8518         let events = nodes[2].node.get_and_clear_pending_msg_events();
8519         assert_eq!(events.len(), 1);
8520         let carol_revocation = match events[0] {
8521                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8522                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8523                         (*msg).clone()
8524                 },
8525                 _ => panic!("Unexpected event"),
8526         };
8527         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8528         check_added_monitors!(nodes[1], 1);
8529
8530         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8531         // here's where we put said channel's commitment tx on-chain.
8532         let mut txn_to_broadcast = alice_txn.clone();
8533         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8534         if !go_onchain_before_fulfill {
8535                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8536                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8537                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8538                 if broadcast_alice {
8539                         check_closed_broadcast!(nodes[1], true);
8540                         check_added_monitors!(nodes[1], 1);
8541                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8542                 }
8543                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8544                 if broadcast_alice {
8545                         assert_eq!(bob_txn.len(), 1);
8546                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8547                 } else {
8548                         assert_eq!(bob_txn.len(), 2);
8549                         check_spends!(bob_txn[0], chan_ab.3);
8550                 }
8551         }
8552
8553         // Step (6):
8554         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8555         // broadcasted commitment transaction.
8556         {
8557                 let script_weight = match broadcast_alice {
8558                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8559                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8560                 };
8561                 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8562                 // Bob force-closed and broadcasts the commitment transaction along with a
8563                 // HTLC-output-claiming transaction.
8564                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8565                 if broadcast_alice {
8566                         assert_eq!(bob_txn.len(), 1);
8567                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8568                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8569                 } else {
8570                         assert_eq!(bob_txn.len(), 2);
8571                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8572                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8573                 }
8574         }
8575 }
8576
8577 #[test]
8578 fn test_onchain_htlc_settlement_after_close() {
8579         do_test_onchain_htlc_settlement_after_close(true, true);
8580         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8581         do_test_onchain_htlc_settlement_after_close(true, false);
8582         do_test_onchain_htlc_settlement_after_close(false, false);
8583 }
8584
8585 #[test]
8586 fn test_duplicate_temporary_channel_id_from_different_peers() {
8587         // Tests that we can accept two different `OpenChannel` requests with the same
8588         // `temporary_channel_id`, as long as they are from different peers.
8589         let chanmon_cfgs = create_chanmon_cfgs(3);
8590         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8591         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8592         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8593
8594         // Create an first channel channel
8595         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8596         let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8597
8598         // Create an second channel
8599         nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8600         let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8601
8602         // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8603         // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8604         open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8605
8606         // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8607         // `temporary_channel_id` as they are from different peers.
8608         nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8609         {
8610                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8611                 assert_eq!(events.len(), 1);
8612                 match &events[0] {
8613                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8614                                 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8615                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8616                         },
8617                         _ => panic!("Unexpected event"),
8618                 }
8619         }
8620
8621         nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8622         {
8623                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8624                 assert_eq!(events.len(), 1);
8625                 match &events[0] {
8626                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8627                                 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8628                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8629                         },
8630                         _ => panic!("Unexpected event"),
8631                 }
8632         }
8633 }
8634
8635 #[test]
8636 fn test_duplicate_chan_id() {
8637         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8638         // already open we reject it and keep the old channel.
8639         //
8640         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8641         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8642         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8643         // updating logic for the existing channel.
8644         let chanmon_cfgs = create_chanmon_cfgs(2);
8645         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8646         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8647         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8648
8649         // Create an initial channel
8650         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8651         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8652         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8653         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()));
8654
8655         // Try to create a second channel with the same temporary_channel_id as the first and check
8656         // that it is rejected.
8657         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8658         {
8659                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8660                 assert_eq!(events.len(), 1);
8661                 match events[0] {
8662                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8663                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8664                                 // first (valid) and second (invalid) channels are closed, given they both have
8665                                 // the same non-temporary channel_id. However, currently we do not, so we just
8666                                 // move forward with it.
8667                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8668                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8669                         },
8670                         _ => panic!("Unexpected event"),
8671                 }
8672         }
8673
8674         // Move the first channel through the funding flow...
8675         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8676
8677         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8678         check_added_monitors!(nodes[0], 0);
8679
8680         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8681         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8682         {
8683                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8684                 assert_eq!(added_monitors.len(), 1);
8685                 assert_eq!(added_monitors[0].0, funding_output);
8686                 added_monitors.clear();
8687         }
8688         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8689
8690         let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8691         let channel_id = funding_outpoint.to_channel_id();
8692
8693         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8694         // temporary one).
8695
8696         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8697         // Technically this is allowed by the spec, but we don't support it and there's little reason
8698         // to. Still, it shouldn't cause any other issues.
8699         open_chan_msg.temporary_channel_id = channel_id;
8700         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8701         {
8702                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8703                 assert_eq!(events.len(), 1);
8704                 match events[0] {
8705                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8706                                 // Technically, at this point, nodes[1] would be justified in thinking both
8707                                 // channels are closed, but currently we do not, so we just move forward with it.
8708                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8709                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8710                         },
8711                         _ => panic!("Unexpected event"),
8712                 }
8713         }
8714
8715         // Now try to create a second channel which has a duplicate funding output.
8716         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8717         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8718         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
8719         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()));
8720         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8721
8722         let funding_created = {
8723                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8724                 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
8725                 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
8726                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8727                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8728                 // channelmanager in a possibly nonsense state instead).
8729                 let mut as_chan = a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8730                 let logger = test_utils::TestLogger::new();
8731                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8732         };
8733         check_added_monitors!(nodes[0], 0);
8734         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8735         // At this point we'll look up if the channel_id is present and immediately fail the channel
8736         // without trying to persist the `ChannelMonitor`.
8737         check_added_monitors!(nodes[1], 0);
8738
8739         // ...still, nodes[1] will reject the duplicate channel.
8740         {
8741                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8742                 assert_eq!(events.len(), 1);
8743                 match events[0] {
8744                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8745                                 // Technically, at this point, nodes[1] would be justified in thinking both
8746                                 // channels are closed, but currently we do not, so we just move forward with it.
8747                                 assert_eq!(msg.channel_id, channel_id);
8748                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8749                         },
8750                         _ => panic!("Unexpected event"),
8751                 }
8752         }
8753
8754         // finally, finish creating the original channel and send a payment over it to make sure
8755         // everything is functional.
8756         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8757         {
8758                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8759                 assert_eq!(added_monitors.len(), 1);
8760                 assert_eq!(added_monitors[0].0, funding_output);
8761                 added_monitors.clear();
8762         }
8763
8764         let events_4 = nodes[0].node.get_and_clear_pending_events();
8765         assert_eq!(events_4.len(), 0);
8766         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8767         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8768
8769         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8770         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
8771         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8772
8773         send_payment(&nodes[0], &[&nodes[1]], 8000000);
8774 }
8775
8776 #[test]
8777 fn test_error_chans_closed() {
8778         // Test that we properly handle error messages, closing appropriate channels.
8779         //
8780         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8781         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8782         // we can test various edge cases around it to ensure we don't regress.
8783         let chanmon_cfgs = create_chanmon_cfgs(3);
8784         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8785         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8786         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8787
8788         // Create some initial channels
8789         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8790         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8791         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
8792
8793         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8794         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8795         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8796
8797         // Closing a channel from a different peer has no effect
8798         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8799         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8800
8801         // Closing one channel doesn't impact others
8802         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8803         check_added_monitors!(nodes[0], 1);
8804         check_closed_broadcast!(nodes[0], false);
8805         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
8806         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8807         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8808         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);
8809         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);
8810
8811         // A null channel ID should close all channels
8812         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8813         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8814         check_added_monitors!(nodes[0], 2);
8815         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
8816         let events = nodes[0].node.get_and_clear_pending_msg_events();
8817         assert_eq!(events.len(), 2);
8818         match events[0] {
8819                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8820                         assert_eq!(msg.contents.flags & 2, 2);
8821                 },
8822                 _ => panic!("Unexpected event"),
8823         }
8824         match events[1] {
8825                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8826                         assert_eq!(msg.contents.flags & 2, 2);
8827                 },
8828                 _ => panic!("Unexpected event"),
8829         }
8830         // Note that at this point users of a standard PeerHandler will end up calling
8831         // peer_disconnected.
8832         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8833         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8834
8835         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
8836         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8837         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8838 }
8839
8840 #[test]
8841 fn test_invalid_funding_tx() {
8842         // Test that we properly handle invalid funding transactions sent to us from a peer.
8843         //
8844         // Previously, all other major lightning implementations had failed to properly sanitize
8845         // funding transactions from their counterparties, leading to a multi-implementation critical
8846         // security vulnerability (though we always sanitized properly, we've previously had
8847         // un-released crashes in the sanitization process).
8848         //
8849         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
8850         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
8851         // gave up on it. We test this here by generating such a transaction.
8852         let chanmon_cfgs = create_chanmon_cfgs(2);
8853         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8854         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8855         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8856
8857         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
8858         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()));
8859         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()));
8860
8861         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
8862
8863         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
8864         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
8865         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
8866         // its length.
8867         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
8868         let wit_program_script: Script = wit_program.into();
8869         for output in tx.output.iter_mut() {
8870                 // Make the confirmed funding transaction have a bogus script_pubkey
8871                 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
8872         }
8873
8874         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
8875         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()));
8876         check_added_monitors!(nodes[1], 1);
8877
8878         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()));
8879         check_added_monitors!(nodes[0], 1);
8880
8881         let events_1 = nodes[0].node.get_and_clear_pending_events();
8882         assert_eq!(events_1.len(), 0);
8883
8884         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8885         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8886         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
8887
8888         let expected_err = "funding tx had wrong script/value or output index";
8889         confirm_transaction_at(&nodes[1], &tx, 1);
8890         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8891         check_added_monitors!(nodes[1], 1);
8892         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
8893         assert_eq!(events_2.len(), 1);
8894         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
8895                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8896                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
8897                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
8898                 } else { panic!(); }
8899         } else { panic!(); }
8900         assert_eq!(nodes[1].node.list_channels().len(), 0);
8901
8902         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
8903         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
8904         // as its not 32 bytes long.
8905         let mut spend_tx = Transaction {
8906                 version: 2i32, lock_time: PackedLockTime::ZERO,
8907                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
8908                         previous_output: BitcoinOutPoint {
8909                                 txid: tx.txid(),
8910                                 vout: idx as u32,
8911                         },
8912                         script_sig: Script::new(),
8913                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
8914                         witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
8915                 }).collect(),
8916                 output: vec![TxOut {
8917                         value: 1000,
8918                         script_pubkey: Script::new(),
8919                 }]
8920         };
8921         check_spends!(spend_tx, tx);
8922         mine_transaction(&nodes[1], &spend_tx);
8923 }
8924
8925 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
8926         // In the first version of the chain::Confirm interface, after a refactor was made to not
8927         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
8928         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
8929         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
8930         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
8931         // spending transaction until height N+1 (or greater). This was due to the way
8932         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
8933         // spending transaction at the height the input transaction was confirmed at, not whether we
8934         // should broadcast a spending transaction at the current height.
8935         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
8936         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
8937         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
8938         // until we learned about an additional block.
8939         //
8940         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
8941         // aren't broadcasting transactions too early (ie not broadcasting them at all).
8942         let chanmon_cfgs = create_chanmon_cfgs(3);
8943         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8944         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8945         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8946         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
8947
8948         create_announced_chan_between_nodes(&nodes, 0, 1);
8949         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
8950         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
8951         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
8952         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
8953
8954         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
8955         check_closed_broadcast!(nodes[1], true);
8956         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8957         check_added_monitors!(nodes[1], 1);
8958         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
8959         assert_eq!(node_txn.len(), 1);
8960
8961         let conf_height = nodes[1].best_block_info().1;
8962         if !test_height_before_timelock {
8963                 connect_blocks(&nodes[1], 24 * 6);
8964         }
8965         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
8966                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
8967         if test_height_before_timelock {
8968                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
8969                 // generate any events or broadcast any transactions
8970                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
8971                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
8972         } else {
8973                 // We should broadcast an HTLC transaction spending our funding transaction first
8974                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
8975                 assert_eq!(spending_txn.len(), 2);
8976                 assert_eq!(spending_txn[0], node_txn[0]);
8977                 check_spends!(spending_txn[1], node_txn[0]);
8978                 // We should also generate a SpendableOutputs event with the to_self output (as its
8979                 // timelock is up).
8980                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
8981                 assert_eq!(descriptor_spend_txn.len(), 1);
8982
8983                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
8984                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
8985                 // additional block built on top of the current chain.
8986                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
8987                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
8988                 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 }]);
8989                 check_added_monitors!(nodes[1], 1);
8990
8991                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8992                 assert!(updates.update_add_htlcs.is_empty());
8993                 assert!(updates.update_fulfill_htlcs.is_empty());
8994                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8995                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8996                 assert!(updates.update_fee.is_none());
8997                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
8998                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
8999                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9000         }
9001 }
9002
9003 #[test]
9004 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9005         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9006         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9007 }
9008
9009 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9010         let chanmon_cfgs = create_chanmon_cfgs(2);
9011         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9012         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9013         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9014
9015         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9016
9017         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9018                 .with_features(nodes[1].node.invoice_features());
9019         let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9020
9021         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9022
9023         {
9024                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9025                 check_added_monitors!(nodes[0], 1);
9026                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9027                 assert_eq!(events.len(), 1);
9028                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9029                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9030                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9031         }
9032         expect_pending_htlcs_forwardable!(nodes[1]);
9033         expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9034
9035         {
9036                 // Note that we use a different PaymentId here to allow us to duplicativly pay
9037                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9038                 check_added_monitors!(nodes[0], 1);
9039                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9040                 assert_eq!(events.len(), 1);
9041                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9042                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9043                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9044                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9045                 // assume the second is a privacy attack (no longer particularly relevant
9046                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9047                 // the first HTLC delivered above.
9048         }
9049
9050         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9051         nodes[1].node.process_pending_htlc_forwards();
9052
9053         if test_for_second_fail_panic {
9054                 // Now we go fail back the first HTLC from the user end.
9055                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9056
9057                 let expected_destinations = vec![
9058                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9059                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9060                 ];
9061                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],  expected_destinations);
9062                 nodes[1].node.process_pending_htlc_forwards();
9063
9064                 check_added_monitors!(nodes[1], 1);
9065                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9066                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9067
9068                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9069                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9070                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9071
9072                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9073                 assert_eq!(failure_events.len(), 4);
9074                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9075                 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9076                 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9077                 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9078         } else {
9079                 // Let the second HTLC fail and claim the first
9080                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9081                 nodes[1].node.process_pending_htlc_forwards();
9082
9083                 check_added_monitors!(nodes[1], 1);
9084                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9085                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9086                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9087
9088                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9089
9090                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9091         }
9092 }
9093
9094 #[test]
9095 fn test_dup_htlc_second_fail_panic() {
9096         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9097         // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9098         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9099         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9100         do_test_dup_htlc_second_rejected(true);
9101 }
9102
9103 #[test]
9104 fn test_dup_htlc_second_rejected() {
9105         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9106         // simply reject the second HTLC but are still able to claim the first HTLC.
9107         do_test_dup_htlc_second_rejected(false);
9108 }
9109
9110 #[test]
9111 fn test_inconsistent_mpp_params() {
9112         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9113         // such HTLC and allow the second to stay.
9114         let chanmon_cfgs = create_chanmon_cfgs(4);
9115         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9116         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9117         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9118
9119         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9120         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9121         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9122         let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9123
9124         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9125                 .with_features(nodes[3].node.invoice_features());
9126         let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9127         assert_eq!(route.paths.len(), 2);
9128         route.paths.sort_by(|path_a, _| {
9129                 // Sort the path so that the path through nodes[1] comes first
9130                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9131                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9132         });
9133         let payment_params_opt = Some(payment_params);
9134
9135         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9136
9137         let cur_height = nodes[0].best_block_info().1;
9138         let payment_id = PaymentId([42; 32]);
9139
9140         let session_privs = {
9141                 // We create a fake route here so that we start with three pending HTLCs, which we'll
9142                 // ultimately have, just not right away.
9143                 let mut dup_route = route.clone();
9144                 dup_route.paths.push(route.paths[1].clone());
9145                 nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(our_payment_secret), payment_id, &dup_route).unwrap()
9146         };
9147         nodes[0].node.test_send_payment_along_path(&route.paths[0], &payment_params_opt, &our_payment_hash, &Some(our_payment_secret), 15_000_000, cur_height, payment_id, &None, session_privs[0]).unwrap();
9148         check_added_monitors!(nodes[0], 1);
9149
9150         {
9151                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9152                 assert_eq!(events.len(), 1);
9153                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9154         }
9155         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9156
9157         nodes[0].node.test_send_payment_along_path(&route.paths[1], &payment_params_opt, &our_payment_hash, &Some(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9158         check_added_monitors!(nodes[0], 1);
9159
9160         {
9161                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9162                 assert_eq!(events.len(), 1);
9163                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9164
9165                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9166                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9167
9168                 expect_pending_htlcs_forwardable!(nodes[2]);
9169                 check_added_monitors!(nodes[2], 1);
9170
9171                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9172                 assert_eq!(events.len(), 1);
9173                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9174
9175                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9176                 check_added_monitors!(nodes[3], 0);
9177                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9178
9179                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9180                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9181                 // post-payment_secrets) and fail back the new HTLC.
9182         }
9183         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9184         nodes[3].node.process_pending_htlc_forwards();
9185         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9186         nodes[3].node.process_pending_htlc_forwards();
9187
9188         check_added_monitors!(nodes[3], 1);
9189
9190         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9191         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9192         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9193
9194         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 }]);
9195         check_added_monitors!(nodes[2], 1);
9196
9197         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9198         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9199         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9200
9201         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9202
9203         nodes[0].node.test_send_payment_along_path(&route.paths[1], &payment_params_opt, &our_payment_hash, &Some(our_payment_secret), 15_000_000, cur_height, payment_id, &None, session_privs[2]).unwrap();
9204         check_added_monitors!(nodes[0], 1);
9205
9206         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9207         assert_eq!(events.len(), 1);
9208         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9209
9210         do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9211         let events = nodes[0].node.get_and_clear_pending_events();
9212         assert_eq!(events.len(), 3);
9213         match events[0] {
9214                 Event::PaymentSent { payment_hash, .. } => { // The payment was abandoned earlier, so the fee paid will be None
9215                         assert_eq!(payment_hash, our_payment_hash);
9216                 },
9217                 _ => panic!("Unexpected event")
9218         }
9219         match events[1] {
9220                 Event::PaymentPathSuccessful { payment_hash, .. } => {
9221                         assert_eq!(payment_hash.unwrap(), our_payment_hash);
9222                 },
9223                 _ => panic!("Unexpected event")
9224         }
9225         match events[2] {
9226                 Event::PaymentPathSuccessful { payment_hash, .. } => {
9227                         assert_eq!(payment_hash.unwrap(), our_payment_hash);
9228                 },
9229                 _ => panic!("Unexpected event")
9230         }
9231 }
9232
9233 #[test]
9234 fn test_keysend_payments_to_public_node() {
9235         let chanmon_cfgs = create_chanmon_cfgs(2);
9236         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9237         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9238         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9239
9240         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9241         let network_graph = nodes[0].network_graph.clone();
9242         let payer_pubkey = nodes[0].node.get_our_node_id();
9243         let payee_pubkey = nodes[1].node.get_our_node_id();
9244         let route_params = RouteParameters {
9245                 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9246                 final_value_msat: 10000,
9247         };
9248         let scorer = test_utils::TestScorer::new();
9249         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9250         let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9251
9252         let test_preimage = PaymentPreimage([42; 32]);
9253         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage), PaymentId(test_preimage.0)).unwrap();
9254         check_added_monitors!(nodes[0], 1);
9255         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9256         assert_eq!(events.len(), 1);
9257         let event = events.pop().unwrap();
9258         let path = vec![&nodes[1]];
9259         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9260         claim_payment(&nodes[0], &path, test_preimage);
9261 }
9262
9263 #[test]
9264 fn test_keysend_payments_to_private_node() {
9265         let chanmon_cfgs = create_chanmon_cfgs(2);
9266         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9267         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9268         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9269
9270         let payer_pubkey = nodes[0].node.get_our_node_id();
9271         let payee_pubkey = nodes[1].node.get_our_node_id();
9272
9273         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
9274         let route_params = RouteParameters {
9275                 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9276                 final_value_msat: 10000,
9277         };
9278         let network_graph = nodes[0].network_graph.clone();
9279         let first_hops = nodes[0].node.list_usable_channels();
9280         let scorer = test_utils::TestScorer::new();
9281         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9282         let route = find_route(
9283                 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9284                 nodes[0].logger, &scorer, &random_seed_bytes
9285         ).unwrap();
9286
9287         let test_preimage = PaymentPreimage([42; 32]);
9288         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage), PaymentId(test_preimage.0)).unwrap();
9289         check_added_monitors!(nodes[0], 1);
9290         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9291         assert_eq!(events.len(), 1);
9292         let event = events.pop().unwrap();
9293         let path = vec![&nodes[1]];
9294         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9295         claim_payment(&nodes[0], &path, test_preimage);
9296 }
9297
9298 #[test]
9299 fn test_double_partial_claim() {
9300         // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9301         // time out, the sender resends only some of the MPP parts, then the user processes the
9302         // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9303         // amount.
9304         let chanmon_cfgs = create_chanmon_cfgs(4);
9305         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9306         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9307         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9308
9309         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9310         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9311         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9312         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9313
9314         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9315         assert_eq!(route.paths.len(), 2);
9316         route.paths.sort_by(|path_a, _| {
9317                 // Sort the path so that the path through nodes[1] comes first
9318                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9319                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9320         });
9321
9322         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9323         // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9324         // amount of time to respond to.
9325
9326         // Connect some blocks to time out the payment
9327         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9328         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9329
9330         let failed_destinations = vec![
9331                 HTLCDestination::FailedPayment { payment_hash },
9332                 HTLCDestination::FailedPayment { payment_hash },
9333         ];
9334         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9335
9336         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
9337
9338         // nodes[1] now retries one of the two paths...
9339         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9340         check_added_monitors!(nodes[0], 2);
9341
9342         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9343         assert_eq!(events.len(), 2);
9344         let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9345         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9346
9347         // At this point nodes[3] has received one half of the payment, and the user goes to handle
9348         // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9349         nodes[3].node.claim_funds(payment_preimage);
9350         check_added_monitors!(nodes[3], 0);
9351         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9352 }
9353
9354 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9355 #[derive(Clone, Copy, PartialEq)]
9356 enum ExposureEvent {
9357         /// Breach occurs at HTLC forwarding (see `send_htlc`)
9358         AtHTLCForward,
9359         /// Breach occurs at HTLC reception (see `update_add_htlc`)
9360         AtHTLCReception,
9361         /// Breach occurs at outbound update_fee (see `send_update_fee`)
9362         AtUpdateFeeOutbound,
9363 }
9364
9365 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9366         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9367         // policy.
9368         //
9369         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9370         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9371         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9372         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9373         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9374         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9375         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9376         // might be available again for HTLC processing once the dust bandwidth has cleared up.
9377
9378         let chanmon_cfgs = create_chanmon_cfgs(2);
9379         let mut config = test_default_channel_config();
9380         config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9381         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9382         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9383         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9384
9385         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9386         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9387         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9388         open_channel.max_accepted_htlcs = 60;
9389         if on_holder_tx {
9390                 open_channel.dust_limit_satoshis = 546;
9391         }
9392         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9393         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9394         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9395
9396         let opt_anchors = false;
9397
9398         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9399
9400         if on_holder_tx {
9401                 let mut node_0_per_peer_lock;
9402                 let mut node_0_peer_state_lock;
9403                 let mut chan = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id);
9404                 chan.holder_dust_limit_satoshis = 546;
9405         }
9406
9407         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9408         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()));
9409         check_added_monitors!(nodes[1], 1);
9410
9411         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()));
9412         check_added_monitors!(nodes[0], 1);
9413
9414         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9415         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9416         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9417
9418         let dust_buffer_feerate = {
9419                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9420                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9421                 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9422                 chan.get_dust_buffer_feerate(None) as u64
9423         };
9424         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;
9425         let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9426
9427         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;
9428         let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9429
9430         let dust_htlc_on_counterparty_tx: u64 = 25;
9431         let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9432
9433         if on_holder_tx {
9434                 if dust_outbound_balance {
9435                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9436                         // Outbound dust balance: 4372 sats
9437                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9438                         for i in 0..dust_outbound_htlc_on_holder_tx {
9439                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9440                                 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); }
9441                         }
9442                 } else {
9443                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9444                         // Inbound dust balance: 4372 sats
9445                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9446                         for _ in 0..dust_inbound_htlc_on_holder_tx {
9447                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9448                         }
9449                 }
9450         } else {
9451                 if dust_outbound_balance {
9452                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9453                         // Outbound dust balance: 5000 sats
9454                         for i in 0..dust_htlc_on_counterparty_tx {
9455                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9456                                 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); }
9457                         }
9458                 } else {
9459                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9460                         // Inbound dust balance: 5000 sats
9461                         for _ in 0..dust_htlc_on_counterparty_tx {
9462                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9463                         }
9464                 }
9465         }
9466
9467         let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9468         if exposure_breach_event == ExposureEvent::AtHTLCForward {
9469                 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 });
9470                 let mut config = UserConfig::default();
9471                 // With default dust exposure: 5000 sats
9472                 if on_holder_tx {
9473                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9474                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9475                         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)));
9476                 } else {
9477                         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)));
9478                 }
9479         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9480                 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 });
9481                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9482                 check_added_monitors!(nodes[1], 1);
9483                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9484                 assert_eq!(events.len(), 1);
9485                 let payment_event = SendEvent::from_event(events.remove(0));
9486                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9487                 // With default dust exposure: 5000 sats
9488                 if on_holder_tx {
9489                         // Outbound dust balance: 6399 sats
9490                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9491                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9492                         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);
9493                 } else {
9494                         // Outbound dust balance: 5200 sats
9495                         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);
9496                 }
9497         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9498                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
9499                 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", ); }
9500                 {
9501                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9502                         *feerate_lock = *feerate_lock * 10;
9503                 }
9504                 nodes[0].node.timer_tick_occurred();
9505                 check_added_monitors!(nodes[0], 1);
9506                 nodes[0].logger.assert_log_contains("lightning::ln::channel".to_string(), "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure".to_string(), 1);
9507         }
9508
9509         let _ = nodes[0].node.get_and_clear_pending_msg_events();
9510         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9511         added_monitors.clear();
9512 }
9513
9514 #[test]
9515 fn test_max_dust_htlc_exposure() {
9516         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9517         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9518         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9519         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9520         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9521         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9522         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9523         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9524         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9525         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9526         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9527         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
9528 }
9529
9530 #[test]
9531 fn test_non_final_funding_tx() {
9532         let chanmon_cfgs = create_chanmon_cfgs(2);
9533         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9534         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9535         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9536
9537         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9538         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9539         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9540         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9541         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9542
9543         let best_height = nodes[0].node.best_block.read().unwrap().height();
9544
9545         let chan_id = *nodes[0].network_chan_count.borrow();
9546         let events = nodes[0].node.get_and_clear_pending_events();
9547         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9548         assert_eq!(events.len(), 1);
9549         let mut tx = match events[0] {
9550                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9551                         // Timelock the transaction _beyond_ the best client height + 2.
9552                         Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 3), input: vec![input], output: vec![TxOut {
9553                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9554                         }]}
9555                 },
9556                 _ => panic!("Unexpected event"),
9557         };
9558         // Transaction should fail as it's evaluated as non-final for propagation.
9559         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9560                 Err(APIError::APIMisuseError { err }) => {
9561                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9562                 },
9563                 _ => panic!()
9564         }
9565
9566         // However, transaction should be accepted if it's in a +2 headroom from best block.
9567         tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9568         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9569         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9570 }
9571
9572 #[test]
9573 fn accept_busted_but_better_fee() {
9574         // If a peer sends us a fee update that is too low, but higher than our previous channel
9575         // feerate, we should accept it. In the future we may want to consider closing the channel
9576         // later, but for now we only accept the update.
9577         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9578         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9579         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9580         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9581
9582         create_chan_between_nodes(&nodes[0], &nodes[1]);
9583
9584         // Set nodes[1] to expect 5,000 sat/kW.
9585         {
9586                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9587                 *feerate_lock = 5000;
9588         }
9589
9590         // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9591         {
9592                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9593                 *feerate_lock = 1000;
9594         }
9595         nodes[0].node.timer_tick_occurred();
9596         check_added_monitors!(nodes[0], 1);
9597
9598         let events = nodes[0].node.get_and_clear_pending_msg_events();
9599         assert_eq!(events.len(), 1);
9600         match events[0] {
9601                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9602                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9603                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9604                 },
9605                 _ => panic!("Unexpected event"),
9606         };
9607
9608         // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9609         // it.
9610         {
9611                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9612                 *feerate_lock = 2000;
9613         }
9614         nodes[0].node.timer_tick_occurred();
9615         check_added_monitors!(nodes[0], 1);
9616
9617         let events = nodes[0].node.get_and_clear_pending_msg_events();
9618         assert_eq!(events.len(), 1);
9619         match events[0] {
9620                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9621                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9622                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9623                 },
9624                 _ => panic!("Unexpected event"),
9625         };
9626
9627         // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9628         // channel.
9629         {
9630                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9631                 *feerate_lock = 1000;
9632         }
9633         nodes[0].node.timer_tick_occurred();
9634         check_added_monitors!(nodes[0], 1);
9635
9636         let events = nodes[0].node.get_and_clear_pending_msg_events();
9637         assert_eq!(events.len(), 1);
9638         match events[0] {
9639                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9640                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9641                         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9642                                 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() });
9643                         check_closed_broadcast!(nodes[1], true);
9644                         check_added_monitors!(nodes[1], 1);
9645                 },
9646                 _ => panic!("Unexpected event"),
9647         };
9648 }
9649
9650 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9651         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9652         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9653         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9654         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9655         let min_final_cltv_expiry_delta = 120;
9656         let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9657                 min_final_cltv_expiry_delta - 2 };
9658         let recv_value = 100_000;
9659
9660         create_chan_between_nodes(&nodes[0], &nodes[1]);
9661
9662         let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
9663         let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
9664                 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
9665                         Some(recv_value), Some(min_final_cltv_expiry_delta));
9666                 (payment_hash, payment_preimage, payment_secret)
9667         } else {
9668                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
9669                 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
9670         };
9671         let route = get_route!(nodes[0], payment_parameters, recv_value, final_cltv_expiry_delta as u32).unwrap();
9672         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9673         check_added_monitors!(nodes[0], 1);
9674         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9675         assert_eq!(events.len(), 1);
9676         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9677         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9678         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9679         expect_pending_htlcs_forwardable!(nodes[1]);
9680
9681         if valid_delta {
9682                 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
9683                         None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
9684
9685                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9686         } else {
9687                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9688
9689                 check_added_monitors!(nodes[1], 1);
9690
9691                 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9692                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
9693                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
9694
9695                 expect_payment_failed!(nodes[0], payment_hash, true);
9696         }
9697 }
9698
9699 #[test]
9700 fn test_payment_with_custom_min_cltv_expiry_delta() {
9701         do_payment_with_custom_min_final_cltv_expiry(false, false);
9702         do_payment_with_custom_min_final_cltv_expiry(false, true);
9703         do_payment_with_custom_min_final_cltv_expiry(true, false);
9704         do_payment_with_custom_min_final_cltv_expiry(true, true);
9705 }