Clean up docs in `keysinterface.rs`
[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::{BaseSign, KeysInterface};
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, 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::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(), channelmanager::provided_init_features(), &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].features = channelmanager::provided_init_features().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(), channelmanager::provided_init_features(), &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(), channelmanager::provided_init_features(), &accept_channel_message);
177         {
178                 let mut lock;
179                 let mut chan = get_channel_ref!(if send_from_initiator { &nodes[1] } else { &nodes[0] }, lock, temp_channel_id);
180                 chan.holder_selected_channel_reserve_satoshis = 0;
181                 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
182         }
183
184         let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
185         let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
186         create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
187
188         // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
189         // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
190         if send_from_initiator {
191                 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
192                         // Note that for outbound channels we have to consider the commitment tx fee and the
193                         // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
194                         // well as an additional HTLC.
195                         - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
196         } else {
197                 send_payment(&nodes[1], &[&nodes[0]], push_amt);
198         }
199 }
200
201 #[test]
202 fn test_counterparty_no_reserve() {
203         do_test_counterparty_no_reserve(true);
204         do_test_counterparty_no_reserve(false);
205 }
206
207 #[test]
208 fn test_async_inbound_update_fee() {
209         let chanmon_cfgs = create_chanmon_cfgs(2);
210         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
211         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
212         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
213         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
214
215         // balancing
216         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
217
218         // A                                        B
219         // update_fee                            ->
220         // send (1) commitment_signed            -.
221         //                                       <- update_add_htlc/commitment_signed
222         // send (2) RAA (awaiting remote revoke) -.
223         // (1) commitment_signed is delivered    ->
224         //                                       .- send (3) RAA (awaiting remote revoke)
225         // (2) RAA is delivered                  ->
226         //                                       .- send (4) commitment_signed
227         //                                       <- (3) RAA is delivered
228         // send (5) commitment_signed            -.
229         //                                       <- (4) commitment_signed is delivered
230         // send (6) RAA                          -.
231         // (5) commitment_signed is delivered    ->
232         //                                       <- RAA
233         // (6) RAA is delivered                  ->
234
235         // First nodes[0] generates an update_fee
236         {
237                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
238                 *feerate_lock += 20;
239         }
240         nodes[0].node.timer_tick_occurred();
241         check_added_monitors!(nodes[0], 1);
242
243         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
244         assert_eq!(events_0.len(), 1);
245         let (update_msg, commitment_signed) = match events_0[0] { // (1)
246                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
247                         (update_fee.as_ref(), commitment_signed)
248                 },
249                 _ => panic!("Unexpected event"),
250         };
251
252         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
253
254         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
255         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
256         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
257         check_added_monitors!(nodes[1], 1);
258
259         let payment_event = {
260                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
261                 assert_eq!(events_1.len(), 1);
262                 SendEvent::from_event(events_1.remove(0))
263         };
264         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
265         assert_eq!(payment_event.msgs.len(), 1);
266
267         // ...now when the messages get delivered everyone should be happy
268         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
269         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
270         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
271         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
272         check_added_monitors!(nodes[0], 1);
273
274         // deliver(1), generate (3):
275         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
276         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
277         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
278         check_added_monitors!(nodes[1], 1);
279
280         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
281         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
282         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
283         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
284         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
285         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
286         assert!(bs_update.update_fee.is_none()); // (4)
287         check_added_monitors!(nodes[1], 1);
288
289         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
290         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
291         assert!(as_update.update_add_htlcs.is_empty()); // (5)
292         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
293         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
294         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
295         assert!(as_update.update_fee.is_none()); // (5)
296         check_added_monitors!(nodes[0], 1);
297
298         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
299         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
300         // only (6) so get_event_msg's assert(len == 1) passes
301         check_added_monitors!(nodes[0], 1);
302
303         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
304         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
305         check_added_monitors!(nodes[1], 1);
306
307         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
308         check_added_monitors!(nodes[0], 1);
309
310         let events_2 = nodes[0].node.get_and_clear_pending_events();
311         assert_eq!(events_2.len(), 1);
312         match events_2[0] {
313                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
314                 _ => panic!("Unexpected event"),
315         }
316
317         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
318         check_added_monitors!(nodes[1], 1);
319 }
320
321 #[test]
322 fn test_update_fee_unordered_raa() {
323         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
324         // crash in an earlier version of the update_fee patch)
325         let chanmon_cfgs = create_chanmon_cfgs(2);
326         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
327         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
328         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
329         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
330
331         // balancing
332         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
333
334         // First nodes[0] generates an update_fee
335         {
336                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
337                 *feerate_lock += 20;
338         }
339         nodes[0].node.timer_tick_occurred();
340         check_added_monitors!(nodes[0], 1);
341
342         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
343         assert_eq!(events_0.len(), 1);
344         let update_msg = match events_0[0] { // (1)
345                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
346                         update_fee.as_ref()
347                 },
348                 _ => panic!("Unexpected event"),
349         };
350
351         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
352
353         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
354         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
355         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
356         check_added_monitors!(nodes[1], 1);
357
358         let payment_event = {
359                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
360                 assert_eq!(events_1.len(), 1);
361                 SendEvent::from_event(events_1.remove(0))
362         };
363         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
364         assert_eq!(payment_event.msgs.len(), 1);
365
366         // ...now when the messages get delivered everyone should be happy
367         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
368         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
369         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
370         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
371         check_added_monitors!(nodes[0], 1);
372
373         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
374         check_added_monitors!(nodes[1], 1);
375
376         // We can't continue, sadly, because our (1) now has a bogus signature
377 }
378
379 #[test]
380 fn test_multi_flight_update_fee() {
381         let chanmon_cfgs = create_chanmon_cfgs(2);
382         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
383         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
384         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
385         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
386
387         // A                                        B
388         // update_fee/commitment_signed          ->
389         //                                       .- send (1) RAA and (2) commitment_signed
390         // update_fee (never committed)          ->
391         // (3) update_fee                        ->
392         // We have to manually generate the above update_fee, it is allowed by the protocol but we
393         // don't track which updates correspond to which revoke_and_ack responses so we're in
394         // AwaitingRAA mode and will not generate the update_fee yet.
395         //                                       <- (1) RAA delivered
396         // (3) is generated and send (4) CS      -.
397         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
398         // know the per_commitment_point to use for it.
399         //                                       <- (2) commitment_signed delivered
400         // revoke_and_ack                        ->
401         //                                          B should send no response here
402         // (4) commitment_signed delivered       ->
403         //                                       <- RAA/commitment_signed delivered
404         // revoke_and_ack                        ->
405
406         // First nodes[0] generates an update_fee
407         let initial_feerate;
408         {
409                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
410                 initial_feerate = *feerate_lock;
411                 *feerate_lock = initial_feerate + 20;
412         }
413         nodes[0].node.timer_tick_occurred();
414         check_added_monitors!(nodes[0], 1);
415
416         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
417         assert_eq!(events_0.len(), 1);
418         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
419                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
420                         (update_fee.as_ref().unwrap(), commitment_signed)
421                 },
422                 _ => panic!("Unexpected event"),
423         };
424
425         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
426         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
427         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
428         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
429         check_added_monitors!(nodes[1], 1);
430
431         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
432         // transaction:
433         {
434                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
435                 *feerate_lock = initial_feerate + 40;
436         }
437         nodes[0].node.timer_tick_occurred();
438         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
439         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
440
441         // Create the (3) update_fee message that nodes[0] will generate before it does...
442         let mut update_msg_2 = msgs::UpdateFee {
443                 channel_id: update_msg_1.channel_id.clone(),
444                 feerate_per_kw: (initial_feerate + 30) as u32,
445         };
446
447         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
448
449         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
450         // Deliver (3)
451         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
452
453         // Deliver (1), generating (3) and (4)
454         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
455         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
456         check_added_monitors!(nodes[0], 1);
457         assert!(as_second_update.update_add_htlcs.is_empty());
458         assert!(as_second_update.update_fulfill_htlcs.is_empty());
459         assert!(as_second_update.update_fail_htlcs.is_empty());
460         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
461         // Check that the update_fee newly generated matches what we delivered:
462         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
463         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
464
465         // Deliver (2) commitment_signed
466         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
467         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
468         check_added_monitors!(nodes[0], 1);
469         // No commitment_signed so get_event_msg's assert(len == 1) passes
470
471         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
472         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
473         check_added_monitors!(nodes[1], 1);
474
475         // Delever (4)
476         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
477         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
478         check_added_monitors!(nodes[1], 1);
479
480         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
481         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
482         check_added_monitors!(nodes[0], 1);
483
484         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
485         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
486         // No commitment_signed so get_event_msg's assert(len == 1) passes
487         check_added_monitors!(nodes[0], 1);
488
489         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
490         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
491         check_added_monitors!(nodes[1], 1);
492 }
493
494 fn do_test_sanity_on_in_flight_opens(steps: u8) {
495         // Previously, we had issues deserializing channels when we hadn't connected the first block
496         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
497         // serialization round-trips and simply do steps towards opening a channel and then drop the
498         // Node objects.
499
500         let chanmon_cfgs = create_chanmon_cfgs(2);
501         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
502         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
503         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
504
505         if steps & 0b1000_0000 != 0{
506                 let block = Block {
507                         header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
508                         txdata: vec![],
509                 };
510                 connect_block(&nodes[0], &block);
511                 connect_block(&nodes[1], &block);
512         }
513
514         if steps & 0x0f == 0 { return; }
515         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
516         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
517
518         if steps & 0x0f == 1 { return; }
519         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
520         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
521
522         if steps & 0x0f == 2 { return; }
523         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
524
525         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
526
527         if steps & 0x0f == 3 { return; }
528         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
529         check_added_monitors!(nodes[0], 0);
530         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
531
532         if steps & 0x0f == 4 { return; }
533         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
534         {
535                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
536                 assert_eq!(added_monitors.len(), 1);
537                 assert_eq!(added_monitors[0].0, funding_output);
538                 added_monitors.clear();
539         }
540         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
541
542         if steps & 0x0f == 5 { return; }
543         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
544         {
545                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
546                 assert_eq!(added_monitors.len(), 1);
547                 assert_eq!(added_monitors[0].0, funding_output);
548                 added_monitors.clear();
549         }
550
551         let events_4 = nodes[0].node.get_and_clear_pending_events();
552         assert_eq!(events_4.len(), 0);
553
554         if steps & 0x0f == 6 { return; }
555         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
556
557         if steps & 0x0f == 7 { return; }
558         confirm_transaction_at(&nodes[0], &tx, 2);
559         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
560         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
561         expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
562 }
563
564 #[test]
565 fn test_sanity_on_in_flight_opens() {
566         do_test_sanity_on_in_flight_opens(0);
567         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
568         do_test_sanity_on_in_flight_opens(1);
569         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
570         do_test_sanity_on_in_flight_opens(2);
571         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
572         do_test_sanity_on_in_flight_opens(3);
573         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
574         do_test_sanity_on_in_flight_opens(4);
575         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
576         do_test_sanity_on_in_flight_opens(5);
577         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
578         do_test_sanity_on_in_flight_opens(6);
579         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
580         do_test_sanity_on_in_flight_opens(7);
581         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
582         do_test_sanity_on_in_flight_opens(8);
583         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
584 }
585
586 #[test]
587 fn test_update_fee_vanilla() {
588         let chanmon_cfgs = create_chanmon_cfgs(2);
589         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
590         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
591         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
592         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
593
594         {
595                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
596                 *feerate_lock += 25;
597         }
598         nodes[0].node.timer_tick_occurred();
599         check_added_monitors!(nodes[0], 1);
600
601         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
602         assert_eq!(events_0.len(), 1);
603         let (update_msg, commitment_signed) = match events_0[0] {
604                         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 } } => {
605                         (update_fee.as_ref(), commitment_signed)
606                 },
607                 _ => panic!("Unexpected event"),
608         };
609         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
610
611         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
612         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
613         check_added_monitors!(nodes[1], 1);
614
615         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
616         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
617         check_added_monitors!(nodes[0], 1);
618
619         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
620         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
621         // No commitment_signed so get_event_msg's assert(len == 1) passes
622         check_added_monitors!(nodes[0], 1);
623
624         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
625         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
626         check_added_monitors!(nodes[1], 1);
627 }
628
629 #[test]
630 fn test_update_fee_that_funder_cannot_afford() {
631         let chanmon_cfgs = create_chanmon_cfgs(2);
632         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
633         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
634         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
635         let channel_value = 5000;
636         let push_sats = 700;
637         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
638         let channel_id = chan.2;
639         let secp_ctx = Secp256k1::new();
640         let default_config = UserConfig::default();
641         let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
642
643         let opt_anchors = false;
644
645         // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
646         // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
647         // calculate two different feerates here - the expected local limit as well as the expected
648         // remote limit.
649         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;
650         let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
651         {
652                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
653                 *feerate_lock = feerate;
654         }
655         nodes[0].node.timer_tick_occurred();
656         check_added_monitors!(nodes[0], 1);
657         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
658
659         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
660
661         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
662
663         // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
664         {
665                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
666
667                 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
668                 assert_eq!(commitment_tx.output.len(), 2);
669                 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
670                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
671                 actual_fee = channel_value - actual_fee;
672                 assert_eq!(total_fee, actual_fee);
673         }
674
675         {
676                 // Increment the feerate by a small constant, accounting for rounding errors
677                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
678                 *feerate_lock += 4;
679         }
680         nodes[0].node.timer_tick_occurred();
681         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
682         check_added_monitors!(nodes[0], 0);
683
684         const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
685
686         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
687         // needed to sign the new commitment tx and (2) sign the new commitment tx.
688         let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
689                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
690                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
691                 let chan_signer = local_chan.get_signer();
692                 let pubkeys = chan_signer.pubkeys();
693                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
694                  pubkeys.funding_pubkey)
695         };
696         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
697                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
698                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
699                 let chan_signer = remote_chan.get_signer();
700                 let pubkeys = chan_signer.pubkeys();
701                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
702                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
703                  pubkeys.funding_pubkey)
704         };
705
706         // Assemble the set of keys we can use for signatures for our commitment_signed message.
707         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
708                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
709
710         let res = {
711                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
712                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
713                 let local_chan_signer = local_chan.get_signer();
714                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
715                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
716                         INITIAL_COMMITMENT_NUMBER - 1,
717                         push_sats,
718                         channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
719                         opt_anchors, local_funding, remote_funding,
720                         commit_tx_keys.clone(),
721                         non_buffer_feerate + 4,
722                         &mut htlcs,
723                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
724                 );
725                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
726         };
727
728         let commit_signed_msg = msgs::CommitmentSigned {
729                 channel_id: chan.2,
730                 signature: res.0,
731                 htlc_signatures: res.1
732         };
733
734         let update_fee = msgs::UpdateFee {
735                 channel_id: chan.2,
736                 feerate_per_kw: non_buffer_feerate + 4,
737         };
738
739         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
740
741         //While producing the commitment_signed response after handling a received update_fee request the
742         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
743         //Should produce and error.
744         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
745         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
746         check_added_monitors!(nodes[1], 1);
747         check_closed_broadcast!(nodes[1], true);
748         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
749 }
750
751 #[test]
752 fn test_update_fee_with_fundee_update_add_htlc() {
753         let chanmon_cfgs = create_chanmon_cfgs(2);
754         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
755         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
756         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
757         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
758
759         // balancing
760         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
761
762         {
763                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
764                 *feerate_lock += 20;
765         }
766         nodes[0].node.timer_tick_occurred();
767         check_added_monitors!(nodes[0], 1);
768
769         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
770         assert_eq!(events_0.len(), 1);
771         let (update_msg, commitment_signed) = match events_0[0] {
772                         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 } } => {
773                         (update_fee.as_ref(), commitment_signed)
774                 },
775                 _ => panic!("Unexpected event"),
776         };
777         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
778         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
779         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
780         check_added_monitors!(nodes[1], 1);
781
782         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
783
784         // nothing happens since node[1] is in AwaitingRemoteRevoke
785         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
786         {
787                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
788                 assert_eq!(added_monitors.len(), 0);
789                 added_monitors.clear();
790         }
791         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
792         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
793         // node[1] has nothing to do
794
795         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
796         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
797         check_added_monitors!(nodes[0], 1);
798
799         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
800         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
801         // No commitment_signed so get_event_msg's assert(len == 1) passes
802         check_added_monitors!(nodes[0], 1);
803         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
804         check_added_monitors!(nodes[1], 1);
805         // AwaitingRemoteRevoke ends here
806
807         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
808         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
809         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
810         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
811         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
812         assert_eq!(commitment_update.update_fee.is_none(), true);
813
814         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
815         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
816         check_added_monitors!(nodes[0], 1);
817         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
818
819         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
820         check_added_monitors!(nodes[1], 1);
821         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
822
823         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
824         check_added_monitors!(nodes[1], 1);
825         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
826         // No commitment_signed so get_event_msg's assert(len == 1) passes
827
828         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
829         check_added_monitors!(nodes[0], 1);
830         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
831
832         expect_pending_htlcs_forwardable!(nodes[0]);
833
834         let events = nodes[0].node.get_and_clear_pending_events();
835         assert_eq!(events.len(), 1);
836         match events[0] {
837                 Event::PaymentClaimable { .. } => { },
838                 _ => panic!("Unexpected event"),
839         };
840
841         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
842
843         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
844         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
845         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
846         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
847         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
848 }
849
850 #[test]
851 fn test_update_fee() {
852         let chanmon_cfgs = create_chanmon_cfgs(2);
853         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
854         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
855         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
856         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
857         let channel_id = chan.2;
858
859         // A                                        B
860         // (1) update_fee/commitment_signed      ->
861         //                                       <- (2) revoke_and_ack
862         //                                       .- send (3) commitment_signed
863         // (4) update_fee/commitment_signed      ->
864         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
865         //                                       <- (3) commitment_signed delivered
866         // send (6) revoke_and_ack               -.
867         //                                       <- (5) deliver revoke_and_ack
868         // (6) deliver revoke_and_ack            ->
869         //                                       .- send (7) commitment_signed in response to (4)
870         //                                       <- (7) deliver commitment_signed
871         // revoke_and_ack                        ->
872
873         // Create and deliver (1)...
874         let feerate;
875         {
876                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
877                 feerate = *feerate_lock;
878                 *feerate_lock = feerate + 20;
879         }
880         nodes[0].node.timer_tick_occurred();
881         check_added_monitors!(nodes[0], 1);
882
883         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
884         assert_eq!(events_0.len(), 1);
885         let (update_msg, commitment_signed) = match events_0[0] {
886                         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 } } => {
887                         (update_fee.as_ref(), commitment_signed)
888                 },
889                 _ => panic!("Unexpected event"),
890         };
891         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
892
893         // Generate (2) and (3):
894         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
895         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
896         check_added_monitors!(nodes[1], 1);
897
898         // Deliver (2):
899         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
900         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
901         check_added_monitors!(nodes[0], 1);
902
903         // Create and deliver (4)...
904         {
905                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
906                 *feerate_lock = feerate + 30;
907         }
908         nodes[0].node.timer_tick_occurred();
909         check_added_monitors!(nodes[0], 1);
910         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
911         assert_eq!(events_0.len(), 1);
912         let (update_msg, commitment_signed) = match events_0[0] {
913                         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 } } => {
914                         (update_fee.as_ref(), commitment_signed)
915                 },
916                 _ => panic!("Unexpected event"),
917         };
918
919         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
920         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
921         check_added_monitors!(nodes[1], 1);
922         // ... creating (5)
923         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
924         // No commitment_signed so get_event_msg's assert(len == 1) passes
925
926         // Handle (3), creating (6):
927         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
928         check_added_monitors!(nodes[0], 1);
929         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
930         // No commitment_signed so get_event_msg's assert(len == 1) passes
931
932         // Deliver (5):
933         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
934         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
935         check_added_monitors!(nodes[0], 1);
936
937         // Deliver (6), creating (7):
938         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
939         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
940         assert!(commitment_update.update_add_htlcs.is_empty());
941         assert!(commitment_update.update_fulfill_htlcs.is_empty());
942         assert!(commitment_update.update_fail_htlcs.is_empty());
943         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
944         assert!(commitment_update.update_fee.is_none());
945         check_added_monitors!(nodes[1], 1);
946
947         // Deliver (7)
948         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
949         check_added_monitors!(nodes[0], 1);
950         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
951         // No commitment_signed so get_event_msg's assert(len == 1) passes
952
953         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
954         check_added_monitors!(nodes[1], 1);
955         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
956
957         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
958         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
959         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
960         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
961         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
962 }
963
964 #[test]
965 fn fake_network_test() {
966         // Simple test which builds a network of ChannelManagers, connects them to each other, and
967         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
968         let chanmon_cfgs = create_chanmon_cfgs(4);
969         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
970         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
971         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
972
973         // Create some initial channels
974         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
975         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
976         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
977
978         // Rebalance the network a bit by relaying one payment through all the channels...
979         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
980         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
981         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
982         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
983
984         // Send some more payments
985         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
986         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
987         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
988
989         // Test failure packets
990         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
991         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
992
993         // Add a new channel that skips 3
994         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
995
996         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
997         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
998         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
999         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1000         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1001         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1002         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1003
1004         // Do some rebalance loop payments, simultaneously
1005         let mut hops = Vec::with_capacity(3);
1006         hops.push(RouteHop {
1007                 pubkey: nodes[2].node.get_our_node_id(),
1008                 node_features: NodeFeatures::empty(),
1009                 short_channel_id: chan_2.0.contents.short_channel_id,
1010                 channel_features: ChannelFeatures::empty(),
1011                 fee_msat: 0,
1012                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1013         });
1014         hops.push(RouteHop {
1015                 pubkey: nodes[3].node.get_our_node_id(),
1016                 node_features: NodeFeatures::empty(),
1017                 short_channel_id: chan_3.0.contents.short_channel_id,
1018                 channel_features: ChannelFeatures::empty(),
1019                 fee_msat: 0,
1020                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1021         });
1022         hops.push(RouteHop {
1023                 pubkey: nodes[1].node.get_our_node_id(),
1024                 node_features: channelmanager::provided_node_features(),
1025                 short_channel_id: chan_4.0.contents.short_channel_id,
1026                 channel_features: channelmanager::provided_channel_features(),
1027                 fee_msat: 1000000,
1028                 cltv_expiry_delta: TEST_FINAL_CLTV,
1029         });
1030         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;
1031         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;
1032         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;
1033
1034         let mut hops = Vec::with_capacity(3);
1035         hops.push(RouteHop {
1036                 pubkey: nodes[3].node.get_our_node_id(),
1037                 node_features: NodeFeatures::empty(),
1038                 short_channel_id: chan_4.0.contents.short_channel_id,
1039                 channel_features: ChannelFeatures::empty(),
1040                 fee_msat: 0,
1041                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1042         });
1043         hops.push(RouteHop {
1044                 pubkey: nodes[2].node.get_our_node_id(),
1045                 node_features: NodeFeatures::empty(),
1046                 short_channel_id: chan_3.0.contents.short_channel_id,
1047                 channel_features: ChannelFeatures::empty(),
1048                 fee_msat: 0,
1049                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1050         });
1051         hops.push(RouteHop {
1052                 pubkey: nodes[1].node.get_our_node_id(),
1053                 node_features: channelmanager::provided_node_features(),
1054                 short_channel_id: chan_2.0.contents.short_channel_id,
1055                 channel_features: channelmanager::provided_channel_features(),
1056                 fee_msat: 1000000,
1057                 cltv_expiry_delta: TEST_FINAL_CLTV,
1058         });
1059         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;
1060         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;
1061         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;
1062
1063         // Claim the rebalances...
1064         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1065         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1066
1067         // Close down the channels...
1068         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1069         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1070         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1071         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1072         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1073         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1074         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1075         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1076         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1077         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1078         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1079         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1080 }
1081
1082 #[test]
1083 fn holding_cell_htlc_counting() {
1084         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1085         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1086         // commitment dance rounds.
1087         let chanmon_cfgs = create_chanmon_cfgs(3);
1088         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1089         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1090         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1091         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1092         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1093
1094         let mut payments = Vec::new();
1095         for _ in 0..crate::ln::channel::OUR_MAX_HTLCS {
1096                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1097                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
1098                 payments.push((payment_preimage, payment_hash));
1099         }
1100         check_added_monitors!(nodes[1], 1);
1101
1102         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1103         assert_eq!(events.len(), 1);
1104         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1105         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1106
1107         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1108         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1109         // another HTLC.
1110         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1111         {
1112                 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 },
1113                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1114                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1115                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1116         }
1117
1118         // This should also be true if we try to forward a payment.
1119         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1120         {
1121                 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1122                 check_added_monitors!(nodes[0], 1);
1123         }
1124
1125         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1126         assert_eq!(events.len(), 1);
1127         let payment_event = SendEvent::from_event(events.pop().unwrap());
1128         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1129
1130         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1131         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1132         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1133         // fails), the second will process the resulting failure and fail the HTLC backward.
1134         expect_pending_htlcs_forwardable!(nodes[1]);
1135         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 }]);
1136         check_added_monitors!(nodes[1], 1);
1137
1138         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1139         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1140         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1141
1142         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1143
1144         // Now forward all the pending HTLCs and claim them back
1145         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1146         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1147         check_added_monitors!(nodes[2], 1);
1148
1149         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1150         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1151         check_added_monitors!(nodes[1], 1);
1152         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1153
1154         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1155         check_added_monitors!(nodes[1], 1);
1156         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1157
1158         for ref update in as_updates.update_add_htlcs.iter() {
1159                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1160         }
1161         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1162         check_added_monitors!(nodes[2], 1);
1163         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1164         check_added_monitors!(nodes[2], 1);
1165         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1166
1167         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1168         check_added_monitors!(nodes[1], 1);
1169         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1170         check_added_monitors!(nodes[1], 1);
1171         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1172
1173         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1174         check_added_monitors!(nodes[2], 1);
1175
1176         expect_pending_htlcs_forwardable!(nodes[2]);
1177
1178         let events = nodes[2].node.get_and_clear_pending_events();
1179         assert_eq!(events.len(), payments.len());
1180         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1181                 match event {
1182                         &Event::PaymentClaimable { ref payment_hash, .. } => {
1183                                 assert_eq!(*payment_hash, *hash);
1184                         },
1185                         _ => panic!("Unexpected event"),
1186                 };
1187         }
1188
1189         for (preimage, _) in payments.drain(..) {
1190                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1191         }
1192
1193         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1194 }
1195
1196 #[test]
1197 fn duplicate_htlc_test() {
1198         // Test that we accept duplicate payment_hash HTLCs across the network and that
1199         // claiming/failing them are all separate and don't affect each other
1200         let chanmon_cfgs = create_chanmon_cfgs(6);
1201         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1202         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1203         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1204
1205         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1206         create_announced_chan_between_nodes(&nodes, 0, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1207         create_announced_chan_between_nodes(&nodes, 1, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1208         create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1209         create_announced_chan_between_nodes(&nodes, 3, 4, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1210         create_announced_chan_between_nodes(&nodes, 3, 5, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1211
1212         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1213
1214         *nodes[0].network_payment_count.borrow_mut() -= 1;
1215         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1216
1217         *nodes[0].network_payment_count.borrow_mut() -= 1;
1218         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1219
1220         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1221         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1222         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1223 }
1224
1225 #[test]
1226 fn test_duplicate_htlc_different_direction_onchain() {
1227         // Test that ChannelMonitor doesn't generate 2 preimage txn
1228         // when we have 2 HTLCs with same preimage that go across a node
1229         // in opposite directions, even with the same payment secret.
1230         let chanmon_cfgs = create_chanmon_cfgs(2);
1231         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1232         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1233         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1234
1235         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1236
1237         // balancing
1238         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1239
1240         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1241
1242         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1243         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200).unwrap();
1244         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1245
1246         // Provide preimage to node 0 by claiming payment
1247         nodes[0].node.claim_funds(payment_preimage);
1248         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1249         check_added_monitors!(nodes[0], 1);
1250
1251         // Broadcast node 1 commitment txn
1252         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1253
1254         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1255         let mut has_both_htlcs = 0; // check htlcs match ones committed
1256         for outp in remote_txn[0].output.iter() {
1257                 if outp.value == 800_000 / 1000 {
1258                         has_both_htlcs += 1;
1259                 } else if outp.value == 900_000 / 1000 {
1260                         has_both_htlcs += 1;
1261                 }
1262         }
1263         assert_eq!(has_both_htlcs, 2);
1264
1265         mine_transaction(&nodes[0], &remote_txn[0]);
1266         check_added_monitors!(nodes[0], 1);
1267         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1268         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1269
1270         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1271         assert_eq!(claim_txn.len(), 5);
1272
1273         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1274         check_spends!(claim_txn[1], chan_1.3); // Alternative commitment tx
1275         check_spends!(claim_txn[2], claim_txn[1]); // HTLC spend in alternative commitment tx
1276
1277         check_spends!(claim_txn[3], remote_txn[0]);
1278         check_spends!(claim_txn[4], remote_txn[0]);
1279         let preimage_tx = &claim_txn[0];
1280         let (preimage_bump_tx, timeout_tx) = if claim_txn[3].input[0].previous_output == preimage_tx.input[0].previous_output {
1281                 (&claim_txn[3], &claim_txn[4])
1282         } else {
1283                 (&claim_txn[4], &claim_txn[3])
1284         };
1285
1286         assert_eq!(preimage_tx.input.len(), 1);
1287         assert_eq!(preimage_bump_tx.input.len(), 1);
1288
1289         assert_eq!(preimage_tx.input.len(), 1);
1290         assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1291         assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1292
1293         assert_eq!(timeout_tx.input.len(), 1);
1294         assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1295         check_spends!(timeout_tx, remote_txn[0]);
1296         assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1297
1298         let events = nodes[0].node.get_and_clear_pending_msg_events();
1299         assert_eq!(events.len(), 3);
1300         for e in events {
1301                 match e {
1302                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1303                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1304                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1305                                 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1306                         },
1307                         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, .. } } => {
1308                                 assert!(update_add_htlcs.is_empty());
1309                                 assert!(update_fail_htlcs.is_empty());
1310                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1311                                 assert!(update_fail_malformed_htlcs.is_empty());
1312                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1313                         },
1314                         _ => panic!("Unexpected event"),
1315                 }
1316         }
1317 }
1318
1319 #[test]
1320 fn test_basic_channel_reserve() {
1321         let chanmon_cfgs = create_chanmon_cfgs(2);
1322         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1323         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1324         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1325         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1326
1327         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1328         let channel_reserve = chan_stat.channel_reserve_msat;
1329
1330         // The 2* and +1 are for the fee spike reserve.
1331         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1, get_opt_anchors!(nodes[0], chan.2));
1332         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1333         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1334         let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1335         match err {
1336                 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1337                         match &fails[0] {
1338                                 &APIError::ChannelUnavailable{ref err} =>
1339                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1340                                 _ => panic!("Unexpected error variant"),
1341                         }
1342                 },
1343                 _ => panic!("Unexpected error variant"),
1344         }
1345         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1346         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);
1347
1348         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1349 }
1350
1351 #[test]
1352 fn test_fee_spike_violation_fails_htlc() {
1353         let chanmon_cfgs = create_chanmon_cfgs(2);
1354         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1355         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1356         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1357         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1358
1359         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1360         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1361         let secp_ctx = Secp256k1::new();
1362         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1363
1364         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1365
1366         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1367         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1368         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1369         let msg = msgs::UpdateAddHTLC {
1370                 channel_id: chan.2,
1371                 htlc_id: 0,
1372                 amount_msat: htlc_msat,
1373                 payment_hash: payment_hash,
1374                 cltv_expiry: htlc_cltv,
1375                 onion_routing_packet: onion_packet,
1376         };
1377
1378         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1379
1380         // Now manually create the commitment_signed message corresponding to the update_add
1381         // nodes[0] just sent. In the code for construction of this message, "local" refers
1382         // to the sender of the message, and "remote" refers to the receiver.
1383
1384         let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1385
1386         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1387
1388         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1389         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1390         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1391                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1392                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1393                 let chan_signer = local_chan.get_signer();
1394                 // Make the signer believe we validated another commitment, so we can release the secret
1395                 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1396
1397                 let pubkeys = chan_signer.pubkeys();
1398                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1399                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1400                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1401                  chan_signer.pubkeys().funding_pubkey)
1402         };
1403         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1404                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1405                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1406                 let chan_signer = remote_chan.get_signer();
1407                 let pubkeys = chan_signer.pubkeys();
1408                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1409                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1410                  chan_signer.pubkeys().funding_pubkey)
1411         };
1412
1413         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1414         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1415                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1416
1417         // Build the remote commitment transaction so we can sign it, and then later use the
1418         // signature for the commitment_signed message.
1419         let local_chan_balance = 1313;
1420
1421         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1422                 offered: false,
1423                 amount_msat: 3460001,
1424                 cltv_expiry: htlc_cltv,
1425                 payment_hash,
1426                 transaction_output_index: Some(1),
1427         };
1428
1429         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1430
1431         let res = {
1432                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1433                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1434                 let local_chan_signer = local_chan.get_signer();
1435                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1436                         commitment_number,
1437                         95000,
1438                         local_chan_balance,
1439                         local_chan.opt_anchors(), local_funding, remote_funding,
1440                         commit_tx_keys.clone(),
1441                         feerate_per_kw,
1442                         &mut vec![(accepted_htlc_info, ())],
1443                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1444                 );
1445                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1446         };
1447
1448         let commit_signed_msg = msgs::CommitmentSigned {
1449                 channel_id: chan.2,
1450                 signature: res.0,
1451                 htlc_signatures: res.1
1452         };
1453
1454         // Send the commitment_signed message to the nodes[1].
1455         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1456         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1457
1458         // Send the RAA to nodes[1].
1459         let raa_msg = msgs::RevokeAndACK {
1460                 channel_id: chan.2,
1461                 per_commitment_secret: local_secret,
1462                 next_per_commitment_point: next_local_point
1463         };
1464         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1465
1466         let events = nodes[1].node.get_and_clear_pending_msg_events();
1467         assert_eq!(events.len(), 1);
1468         // Make sure the HTLC failed in the way we expect.
1469         match events[0] {
1470                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1471                         assert_eq!(update_fail_htlcs.len(), 1);
1472                         update_fail_htlcs[0].clone()
1473                 },
1474                 _ => panic!("Unexpected event"),
1475         };
1476         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1477                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1478
1479         check_added_monitors!(nodes[1], 2);
1480 }
1481
1482 #[test]
1483 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1484         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1485         // Set the fee rate for the channel very high, to the point where the fundee
1486         // sending any above-dust amount would result in a channel reserve violation.
1487         // In this test we check that we would be prevented from sending an HTLC in
1488         // this situation.
1489         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1490         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1491         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1492         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1493         let default_config = UserConfig::default();
1494         let opt_anchors = false;
1495
1496         let mut push_amt = 100_000_000;
1497         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1498
1499         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1500
1501         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1502
1503         // Sending exactly enough to hit the reserve amount should be accepted
1504         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1505                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1506         }
1507
1508         // However one more HTLC should be significantly over the reserve amount and fail.
1509         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1510         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 },
1511                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1512         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1513         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);
1514 }
1515
1516 #[test]
1517 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1518         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1519         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1520         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1521         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1522         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1523         let default_config = UserConfig::default();
1524         let opt_anchors = false;
1525
1526         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1527         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1528         // transaction fee with 0 HTLCs (183 sats)).
1529         let mut push_amt = 100_000_000;
1530         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1531         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1532         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1533
1534         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1535         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1536                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1537         }
1538
1539         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1540         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1541         let secp_ctx = Secp256k1::new();
1542         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1543         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1544         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1545         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1546         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1547         let msg = msgs::UpdateAddHTLC {
1548                 channel_id: chan.2,
1549                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1550                 amount_msat: htlc_msat,
1551                 payment_hash: payment_hash,
1552                 cltv_expiry: htlc_cltv,
1553                 onion_routing_packet: onion_packet,
1554         };
1555
1556         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1557         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1558         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);
1559         assert_eq!(nodes[0].node.list_channels().len(), 0);
1560         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1561         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1562         check_added_monitors!(nodes[0], 1);
1563         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() });
1564 }
1565
1566 #[test]
1567 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1568         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1569         // calculating our commitment transaction fee (this was previously broken).
1570         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1571         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1572
1573         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1574         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1575         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1576         let default_config = UserConfig::default();
1577         let opt_anchors = false;
1578
1579         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1580         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1581         // transaction fee with 0 HTLCs (183 sats)).
1582         let mut push_amt = 100_000_000;
1583         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1584         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1585         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1586
1587         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1588                 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1589         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1590         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1591         // commitment transaction fee.
1592         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1593
1594         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1595         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1596                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1597         }
1598
1599         // One more than the dust amt should fail, however.
1600         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1601         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 },
1602                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1603 }
1604
1605 #[test]
1606 fn test_chan_init_feerate_unaffordability() {
1607         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1608         // channel reserve and feerate requirements.
1609         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1610         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1611         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1612         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1613         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1614         let default_config = UserConfig::default();
1615         let opt_anchors = false;
1616
1617         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1618         // HTLC.
1619         let mut push_amt = 100_000_000;
1620         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1621         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1622                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1623
1624         // During open, we don't have a "counterparty channel reserve" to check against, so that
1625         // requirement only comes into play on the open_channel handling side.
1626         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1627         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1628         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1629         open_channel_msg.push_msat += 1;
1630         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel_msg);
1631
1632         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1633         assert_eq!(msg_events.len(), 1);
1634         match msg_events[0] {
1635                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1636                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1637                 },
1638                 _ => panic!("Unexpected event"),
1639         }
1640 }
1641
1642 #[test]
1643 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1644         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1645         // calculating our counterparty's commitment transaction fee (this was previously broken).
1646         let chanmon_cfgs = create_chanmon_cfgs(2);
1647         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1648         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1649         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1650         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1651
1652         let payment_amt = 46000; // Dust amount
1653         // In the previous code, these first four payments would succeed.
1654         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1655         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1656         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1657         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1658
1659         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
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         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1665
1666         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1667         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1668         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1669         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1670 }
1671
1672 #[test]
1673 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1674         let chanmon_cfgs = create_chanmon_cfgs(3);
1675         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1676         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1677         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1678         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1679         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1680
1681         let feemsat = 239;
1682         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1683         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1684         let feerate = get_feerate!(nodes[0], chan.2);
1685         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
1686
1687         // Add a 2* and +1 for the fee spike reserve.
1688         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1689         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;
1690         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1691
1692         // Add a pending HTLC.
1693         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1694         let payment_event_1 = {
1695                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1696                 check_added_monitors!(nodes[0], 1);
1697
1698                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1699                 assert_eq!(events.len(), 1);
1700                 SendEvent::from_event(events.remove(0))
1701         };
1702         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1703
1704         // Attempt to trigger a channel reserve violation --> payment failure.
1705         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1706         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;
1707         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1708         let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1709
1710         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1711         let secp_ctx = Secp256k1::new();
1712         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1713         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1714         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1715         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1716         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1717         let msg = msgs::UpdateAddHTLC {
1718                 channel_id: chan.2,
1719                 htlc_id: 1,
1720                 amount_msat: htlc_msat + 1,
1721                 payment_hash: our_payment_hash_1,
1722                 cltv_expiry: htlc_cltv,
1723                 onion_routing_packet: onion_packet,
1724         };
1725
1726         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1727         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1728         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1729         assert_eq!(nodes[1].node.list_channels().len(), 1);
1730         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1731         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1732         check_added_monitors!(nodes[1], 1);
1733         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1734 }
1735
1736 #[test]
1737 fn test_inbound_outbound_capacity_is_not_zero() {
1738         let chanmon_cfgs = create_chanmon_cfgs(2);
1739         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1740         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1741         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1742         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1743         let channels0 = node_chanmgrs[0].list_channels();
1744         let channels1 = node_chanmgrs[1].list_channels();
1745         let default_config = UserConfig::default();
1746         assert_eq!(channels0.len(), 1);
1747         assert_eq!(channels1.len(), 1);
1748
1749         let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1750         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1751         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1752
1753         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1754         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1755 }
1756
1757 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1758         (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1759 }
1760
1761 #[test]
1762 fn test_channel_reserve_holding_cell_htlcs() {
1763         let chanmon_cfgs = create_chanmon_cfgs(3);
1764         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1765         // When this test was written, the default base fee floated based on the HTLC count.
1766         // It is now fixed, so we simply set the fee to the expected value here.
1767         let mut config = test_default_channel_config();
1768         config.channel_config.forwarding_fee_base_msat = 239;
1769         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1770         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1771         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1772         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1773
1774         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1775         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1776
1777         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1778         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1779
1780         macro_rules! expect_forward {
1781                 ($node: expr) => {{
1782                         let mut events = $node.node.get_and_clear_pending_msg_events();
1783                         assert_eq!(events.len(), 1);
1784                         check_added_monitors!($node, 1);
1785                         let payment_event = SendEvent::from_event(events.remove(0));
1786                         payment_event
1787                 }}
1788         }
1789
1790         let feemsat = 239; // set above
1791         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1792         let feerate = get_feerate!(nodes[0], chan_1.2);
1793         let opt_anchors = get_opt_anchors!(nodes[0], chan_1.2);
1794
1795         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1796
1797         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1798         {
1799                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1800                         .with_features(channelmanager::provided_invoice_features()).with_max_channel_saturation_power_of_half(0);
1801                 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);
1802                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1803                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1804
1805                 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 },
1806                         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)));
1807                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1808                 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);
1809         }
1810
1811         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1812         // nodes[0]'s wealth
1813         loop {
1814                 let amt_msat = recv_value_0 + total_fee_msat;
1815                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1816                 // Also, ensure that each payment has enough to be over the dust limit to
1817                 // ensure it'll be included in each commit tx fee calculation.
1818                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1819                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1820                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1821                         break;
1822                 }
1823
1824                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1825                         .with_features(channelmanager::provided_invoice_features()).with_max_channel_saturation_power_of_half(0);
1826                 let route = get_route!(nodes[0], payment_params, recv_value_0, TEST_FINAL_CLTV).unwrap();
1827                 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1828                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1829
1830                 let (stat01_, stat11_, stat12_, stat22_) = (
1831                         get_channel_value_stat!(nodes[0], chan_1.2),
1832                         get_channel_value_stat!(nodes[1], chan_1.2),
1833                         get_channel_value_stat!(nodes[1], chan_2.2),
1834                         get_channel_value_stat!(nodes[2], chan_2.2),
1835                 );
1836
1837                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1838                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1839                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1840                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1841                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1842         }
1843
1844         // adding pending output.
1845         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1846         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1847         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1848         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1849         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1850         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1851         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1852         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1853         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1854         // policy.
1855         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1856         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1857         let amt_msat_1 = recv_value_1 + total_fee_msat;
1858
1859         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);
1860         let payment_event_1 = {
1861                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1862                 check_added_monitors!(nodes[0], 1);
1863
1864                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1865                 assert_eq!(events.len(), 1);
1866                 SendEvent::from_event(events.remove(0))
1867         };
1868         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1869
1870         // channel reserve test with htlc pending output > 0
1871         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1872         {
1873                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1874                 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 },
1875                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1876                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1877         }
1878
1879         // split the rest to test holding cell
1880         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1881         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1882         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1883         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1884         {
1885                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1886                 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);
1887         }
1888
1889         // now see if they go through on both sides
1890         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);
1891         // but this will stuck in the holding cell
1892         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1893         check_added_monitors!(nodes[0], 0);
1894         let events = nodes[0].node.get_and_clear_pending_events();
1895         assert_eq!(events.len(), 0);
1896
1897         // test with outbound holding cell amount > 0
1898         {
1899                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1900                 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 },
1901                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1902                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1903                 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);
1904         }
1905
1906         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);
1907         // this will also stuck in the holding cell
1908         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1909         check_added_monitors!(nodes[0], 0);
1910         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1911         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1912
1913         // flush the pending htlc
1914         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1915         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1916         check_added_monitors!(nodes[1], 1);
1917
1918         // the pending htlc should be promoted to committed
1919         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1920         check_added_monitors!(nodes[0], 1);
1921         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1922
1923         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1924         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1925         // No commitment_signed so get_event_msg's assert(len == 1) passes
1926         check_added_monitors!(nodes[0], 1);
1927
1928         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1929         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1930         check_added_monitors!(nodes[1], 1);
1931
1932         expect_pending_htlcs_forwardable!(nodes[1]);
1933
1934         let ref payment_event_11 = expect_forward!(nodes[1]);
1935         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1936         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1937
1938         expect_pending_htlcs_forwardable!(nodes[2]);
1939         expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1940
1941         // flush the htlcs in the holding cell
1942         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1943         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1944         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1945         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1946         expect_pending_htlcs_forwardable!(nodes[1]);
1947
1948         let ref payment_event_3 = expect_forward!(nodes[1]);
1949         assert_eq!(payment_event_3.msgs.len(), 2);
1950         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1951         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1952
1953         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1954         expect_pending_htlcs_forwardable!(nodes[2]);
1955
1956         let events = nodes[2].node.get_and_clear_pending_events();
1957         assert_eq!(events.len(), 2);
1958         match events[0] {
1959                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
1960                         assert_eq!(our_payment_hash_21, *payment_hash);
1961                         assert_eq!(recv_value_21, amount_msat);
1962                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
1963                         assert_eq!(via_channel_id, Some(chan_2.2));
1964                         match &purpose {
1965                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1966                                         assert!(payment_preimage.is_none());
1967                                         assert_eq!(our_payment_secret_21, *payment_secret);
1968                                 },
1969                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1970                         }
1971                 },
1972                 _ => panic!("Unexpected event"),
1973         }
1974         match events[1] {
1975                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
1976                         assert_eq!(our_payment_hash_22, *payment_hash);
1977                         assert_eq!(recv_value_22, amount_msat);
1978                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
1979                         assert_eq!(via_channel_id, Some(chan_2.2));
1980                         match &purpose {
1981                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1982                                         assert!(payment_preimage.is_none());
1983                                         assert_eq!(our_payment_secret_22, *payment_secret);
1984                                 },
1985                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1986                         }
1987                 },
1988                 _ => panic!("Unexpected event"),
1989         }
1990
1991         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1992         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1993         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
1994
1995         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
1996         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
1997         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
1998
1999         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2000         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);
2001         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2002         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2003         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2004
2005         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2006         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2007 }
2008
2009 #[test]
2010 fn channel_reserve_in_flight_removes() {
2011         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2012         // can send to its counterparty, but due to update ordering, the other side may not yet have
2013         // considered those HTLCs fully removed.
2014         // This tests that we don't count HTLCs which will not be included in the next remote
2015         // commitment transaction towards the reserve value (as it implies no commitment transaction
2016         // will be generated which violates the remote reserve value).
2017         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2018         // To test this we:
2019         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2020         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2021         //    you only consider the value of the first HTLC, it may not),
2022         //  * start routing a third HTLC from A to B,
2023         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2024         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2025         //  * deliver the first fulfill from B
2026         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2027         //    claim,
2028         //  * deliver A's response CS and RAA.
2029         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2030         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2031         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2032         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2033         let chanmon_cfgs = create_chanmon_cfgs(2);
2034         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2035         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2036         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2037         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2038
2039         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2040         // Route the first two HTLCs.
2041         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2042         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2043         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2044
2045         // Start routing the third HTLC (this is just used to get everyone in the right state).
2046         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2047         let send_1 = {
2048                 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2049                 check_added_monitors!(nodes[0], 1);
2050                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2051                 assert_eq!(events.len(), 1);
2052                 SendEvent::from_event(events.remove(0))
2053         };
2054
2055         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2056         // initial fulfill/CS.
2057         nodes[1].node.claim_funds(payment_preimage_1);
2058         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2059         check_added_monitors!(nodes[1], 1);
2060         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2061
2062         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2063         // remove the second HTLC when we send the HTLC back from B to A.
2064         nodes[1].node.claim_funds(payment_preimage_2);
2065         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2066         check_added_monitors!(nodes[1], 1);
2067         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2068
2069         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2070         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2071         check_added_monitors!(nodes[0], 1);
2072         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2073         expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2074
2075         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2076         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2077         check_added_monitors!(nodes[1], 1);
2078         // B is already AwaitingRAA, so cant generate a CS here
2079         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2080
2081         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2082         check_added_monitors!(nodes[1], 1);
2083         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2084
2085         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2086         check_added_monitors!(nodes[0], 1);
2087         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2088
2089         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2090         check_added_monitors!(nodes[1], 1);
2091         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2092
2093         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2094         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2095         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2096         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2097         // on-chain as necessary).
2098         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2099         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2100         check_added_monitors!(nodes[0], 1);
2101         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2102         expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2103
2104         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2105         check_added_monitors!(nodes[1], 1);
2106         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2107
2108         expect_pending_htlcs_forwardable!(nodes[1]);
2109         expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2110
2111         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2112         // resolve the second HTLC from A's point of view.
2113         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2114         check_added_monitors!(nodes[0], 1);
2115         expect_payment_path_successful!(nodes[0]);
2116         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2117
2118         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2119         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2120         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2121         let send_2 = {
2122                 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2123                 check_added_monitors!(nodes[1], 1);
2124                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2125                 assert_eq!(events.len(), 1);
2126                 SendEvent::from_event(events.remove(0))
2127         };
2128
2129         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2130         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2131         check_added_monitors!(nodes[0], 1);
2132         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2133
2134         // Now just resolve all the outstanding messages/HTLCs for completeness...
2135
2136         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2137         check_added_monitors!(nodes[1], 1);
2138         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2139
2140         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2141         check_added_monitors!(nodes[1], 1);
2142
2143         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2144         check_added_monitors!(nodes[0], 1);
2145         expect_payment_path_successful!(nodes[0]);
2146         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2147
2148         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2149         check_added_monitors!(nodes[1], 1);
2150         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2151
2152         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2153         check_added_monitors!(nodes[0], 1);
2154
2155         expect_pending_htlcs_forwardable!(nodes[0]);
2156         expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2157
2158         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2159         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2160 }
2161
2162 #[test]
2163 fn channel_monitor_network_test() {
2164         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2165         // tests that ChannelMonitor is able to recover from various states.
2166         let chanmon_cfgs = create_chanmon_cfgs(5);
2167         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2168         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2169         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2170
2171         // Create some initial channels
2172         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2173         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2174         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2175         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2176
2177         // Make sure all nodes are at the same starting height
2178         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2179         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2180         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2181         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2182         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2183
2184         // Rebalance the network a bit by relaying one payment through all the channels...
2185         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2186         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2187         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2188         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2189
2190         // Simple case with no pending HTLCs:
2191         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2192         check_added_monitors!(nodes[1], 1);
2193         check_closed_broadcast!(nodes[1], true);
2194         {
2195                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2196                 assert_eq!(node_txn.len(), 1);
2197                 mine_transaction(&nodes[0], &node_txn[0]);
2198                 check_added_monitors!(nodes[0], 1);
2199                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2200         }
2201         check_closed_broadcast!(nodes[0], true);
2202         assert_eq!(nodes[0].node.list_channels().len(), 0);
2203         assert_eq!(nodes[1].node.list_channels().len(), 1);
2204         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2205         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2206
2207         // One pending HTLC is discarded by the force-close:
2208         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2209
2210         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2211         // broadcasted until we reach the timelock time).
2212         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2213         check_closed_broadcast!(nodes[1], true);
2214         check_added_monitors!(nodes[1], 1);
2215         {
2216                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2217                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2218                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2219                 mine_transaction(&nodes[2], &node_txn[0]);
2220                 check_added_monitors!(nodes[2], 1);
2221                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2222         }
2223         check_closed_broadcast!(nodes[2], true);
2224         assert_eq!(nodes[1].node.list_channels().len(), 0);
2225         assert_eq!(nodes[2].node.list_channels().len(), 1);
2226         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2227         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2228
2229         macro_rules! claim_funds {
2230                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2231                         {
2232                                 $node.node.claim_funds($preimage);
2233                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2234                                 check_added_monitors!($node, 1);
2235
2236                                 let events = $node.node.get_and_clear_pending_msg_events();
2237                                 assert_eq!(events.len(), 1);
2238                                 match events[0] {
2239                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2240                                                 assert!(update_add_htlcs.is_empty());
2241                                                 assert!(update_fail_htlcs.is_empty());
2242                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2243                                         },
2244                                         _ => panic!("Unexpected event"),
2245                                 };
2246                         }
2247                 }
2248         }
2249
2250         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2251         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2252         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2253         check_added_monitors!(nodes[2], 1);
2254         check_closed_broadcast!(nodes[2], true);
2255         let node2_commitment_txid;
2256         {
2257                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2258                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2259                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2260                 node2_commitment_txid = node_txn[0].txid();
2261
2262                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2263                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2264                 mine_transaction(&nodes[3], &node_txn[0]);
2265                 check_added_monitors!(nodes[3], 1);
2266                 check_preimage_claim(&nodes[3], &node_txn);
2267         }
2268         check_closed_broadcast!(nodes[3], true);
2269         assert_eq!(nodes[2].node.list_channels().len(), 0);
2270         assert_eq!(nodes[3].node.list_channels().len(), 1);
2271         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2272         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2273
2274         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2275         // confusing us in the following tests.
2276         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2277
2278         // One pending HTLC to time out:
2279         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2280         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2281         // buffer space).
2282
2283         let (close_chan_update_1, close_chan_update_2) = {
2284                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2285                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2286                 assert_eq!(events.len(), 2);
2287                 let close_chan_update_1 = match events[0] {
2288                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2289                                 msg.clone()
2290                         },
2291                         _ => panic!("Unexpected event"),
2292                 };
2293                 match events[1] {
2294                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2295                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2296                         },
2297                         _ => panic!("Unexpected event"),
2298                 }
2299                 check_added_monitors!(nodes[3], 1);
2300
2301                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2302                 {
2303                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2304                         node_txn.retain(|tx| {
2305                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2306                                         false
2307                                 } else { true }
2308                         });
2309                 }
2310
2311                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2312
2313                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2314                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2315
2316                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2317                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2318                 assert_eq!(events.len(), 2);
2319                 let close_chan_update_2 = match events[0] {
2320                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2321                                 msg.clone()
2322                         },
2323                         _ => panic!("Unexpected event"),
2324                 };
2325                 match events[1] {
2326                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2327                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2328                         },
2329                         _ => panic!("Unexpected event"),
2330                 }
2331                 check_added_monitors!(nodes[4], 1);
2332                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2333
2334                 mine_transaction(&nodes[4], &node_txn[0]);
2335                 check_preimage_claim(&nodes[4], &node_txn);
2336                 (close_chan_update_1, close_chan_update_2)
2337         };
2338         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2339         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2340         assert_eq!(nodes[3].node.list_channels().len(), 0);
2341         assert_eq!(nodes[4].node.list_channels().len(), 0);
2342
2343         assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2344                 ChannelMonitorUpdateStatus::Completed);
2345         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2346         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2347 }
2348
2349 #[test]
2350 fn test_justice_tx() {
2351         // Test justice txn built on revoked HTLC-Success tx, against both sides
2352         let mut alice_config = UserConfig::default();
2353         alice_config.channel_handshake_config.announced_channel = true;
2354         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2355         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2356         let mut bob_config = UserConfig::default();
2357         bob_config.channel_handshake_config.announced_channel = true;
2358         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2359         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2360         let user_cfgs = [Some(alice_config), Some(bob_config)];
2361         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2362         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2363         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2364         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2365         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2366         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2367         *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2368         // Create some new channels:
2369         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2370
2371         // A pending HTLC which will be revoked:
2372         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2373         // Get the will-be-revoked local txn from nodes[0]
2374         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2375         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2376         assert_eq!(revoked_local_txn[0].input.len(), 1);
2377         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2378         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2379         assert_eq!(revoked_local_txn[1].input.len(), 1);
2380         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2381         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2382         // Revoke the old state
2383         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2384
2385         {
2386                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2387                 {
2388                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2389                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2390                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2391
2392                         check_spends!(node_txn[0], revoked_local_txn[0]);
2393                         node_txn.swap_remove(0);
2394                         node_txn.truncate(1);
2395                 }
2396                 check_added_monitors!(nodes[1], 1);
2397                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2398                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2399
2400                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2401                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2402                 // Verify broadcast of revoked HTLC-timeout
2403                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2404                 check_added_monitors!(nodes[0], 1);
2405                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2406                 // Broadcast revoked HTLC-timeout on node 1
2407                 mine_transaction(&nodes[1], &node_txn[1]);
2408                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2409         }
2410         get_announce_close_broadcast_events(&nodes, 0, 1);
2411
2412         assert_eq!(nodes[0].node.list_channels().len(), 0);
2413         assert_eq!(nodes[1].node.list_channels().len(), 0);
2414
2415         // We test justice_tx build by A on B's revoked HTLC-Success tx
2416         // Create some new channels:
2417         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2418         {
2419                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2420                 node_txn.clear();
2421         }
2422
2423         // A pending HTLC which will be revoked:
2424         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2425         // Get the will-be-revoked local txn from B
2426         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2427         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2428         assert_eq!(revoked_local_txn[0].input.len(), 1);
2429         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2430         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2431         // Revoke the old state
2432         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2433         {
2434                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2435                 {
2436                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2437                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2438                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2439
2440                         check_spends!(node_txn[0], revoked_local_txn[0]);
2441                         node_txn.swap_remove(0);
2442                 }
2443                 check_added_monitors!(nodes[0], 1);
2444                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2445
2446                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2447                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2448                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2449                 check_added_monitors!(nodes[1], 1);
2450                 mine_transaction(&nodes[0], &node_txn[1]);
2451                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2452                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2453         }
2454         get_announce_close_broadcast_events(&nodes, 0, 1);
2455         assert_eq!(nodes[0].node.list_channels().len(), 0);
2456         assert_eq!(nodes[1].node.list_channels().len(), 0);
2457 }
2458
2459 #[test]
2460 fn revoked_output_claim() {
2461         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2462         // transaction is broadcast by its counterparty
2463         let chanmon_cfgs = create_chanmon_cfgs(2);
2464         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2465         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2466         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2467         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2468         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2469         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2470         assert_eq!(revoked_local_txn.len(), 1);
2471         // Only output is the full channel value back to nodes[0]:
2472         assert_eq!(revoked_local_txn[0].output.len(), 1);
2473         // Send a payment through, updating everyone's latest commitment txn
2474         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2475
2476         // Inform nodes[1] that nodes[0] broadcast a stale tx
2477         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2478         check_added_monitors!(nodes[1], 1);
2479         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2480         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2481         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2482
2483         check_spends!(node_txn[0], revoked_local_txn[0]);
2484         check_spends!(node_txn[1], chan_1.3);
2485
2486         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2487         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2488         get_announce_close_broadcast_events(&nodes, 0, 1);
2489         check_added_monitors!(nodes[0], 1);
2490         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2491 }
2492
2493 #[test]
2494 fn claim_htlc_outputs_shared_tx() {
2495         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2496         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2497         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2498         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2499         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2500         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2501
2502         // Create some new channel:
2503         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2504
2505         // Rebalance the network to generate htlc in the two directions
2506         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2507         // 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
2508         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2509         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2510
2511         // Get the will-be-revoked local txn from node[0]
2512         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2513         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2514         assert_eq!(revoked_local_txn[0].input.len(), 1);
2515         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2516         assert_eq!(revoked_local_txn[1].input.len(), 1);
2517         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2518         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2519         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2520
2521         //Revoke the old state
2522         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2523
2524         {
2525                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2526                 check_added_monitors!(nodes[0], 1);
2527                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2528                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2529                 check_added_monitors!(nodes[1], 1);
2530                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2531                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2532                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2533
2534                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2535                 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2536
2537                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2538                 check_spends!(node_txn[0], revoked_local_txn[0]);
2539
2540                 let mut witness_lens = BTreeSet::new();
2541                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2542                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2543                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2544                 assert_eq!(witness_lens.len(), 3);
2545                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2546                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2547                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2548
2549                 // Next nodes[1] broadcasts its current local tx state:
2550                 assert_eq!(node_txn[1].input.len(), 1);
2551                 check_spends!(node_txn[1], chan_1.3);
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, channelmanager::provided_init_features(), channelmanager::provided_init_features());
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!(node_txn.len() == 9 || node_txn.len() == 10);
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 1-2-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, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2669         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
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(); // ChannelManager : 3 (commitment tx, 2*htlc-success tx), ChannelMonitor : 2 (2 * HTLC-Success tx)
2705         assert_eq!(node_txn.len(), 5);
2706         assert_eq!(node_txn[0], node_txn[3]);
2707         assert_eq!(node_txn[1], node_txn[4]);
2708         assert_eq!(node_txn[2], commitment_tx[0]);
2709         check_spends!(node_txn[0], commitment_tx[0]);
2710         check_spends!(node_txn[1], commitment_tx[0]);
2711         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2712         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2713         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2714         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2715         assert_eq!(node_txn[0].lock_time.0, 0);
2716         assert_eq!(node_txn[1].lock_time.0, 0);
2717
2718         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2719         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2720         connect_block(&nodes[1], &Block { header, txdata: node_txn});
2721         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2722         {
2723                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2724                 assert_eq!(added_monitors.len(), 1);
2725                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2726                 added_monitors.clear();
2727         }
2728         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2729         assert_eq!(forwarded_events.len(), 3);
2730         match forwarded_events[0] {
2731                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2732                 _ => panic!("Unexpected event"),
2733         }
2734         let chan_id = Some(chan_1.2);
2735         match forwarded_events[1] {
2736                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2737                         assert_eq!(fee_earned_msat, Some(1000));
2738                         assert_eq!(prev_channel_id, chan_id);
2739                         assert_eq!(claim_from_onchain_tx, true);
2740                         assert_eq!(next_channel_id, Some(chan_2.2));
2741                 },
2742                 _ => panic!()
2743         }
2744         match forwarded_events[2] {
2745                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2746                         assert_eq!(fee_earned_msat, Some(1000));
2747                         assert_eq!(prev_channel_id, chan_id);
2748                         assert_eq!(claim_from_onchain_tx, true);
2749                         assert_eq!(next_channel_id, Some(chan_2.2));
2750                 },
2751                 _ => panic!()
2752         }
2753         let events = nodes[1].node.get_and_clear_pending_msg_events();
2754         {
2755                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2756                 assert_eq!(added_monitors.len(), 2);
2757                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2758                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2759                 added_monitors.clear();
2760         }
2761         assert_eq!(events.len(), 3);
2762         match events[0] {
2763                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2764                 _ => panic!("Unexpected event"),
2765         }
2766         match events[1] {
2767                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2768                 _ => panic!("Unexpected event"),
2769         }
2770
2771         match events[2] {
2772                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
2773                         assert!(update_add_htlcs.is_empty());
2774                         assert!(update_fail_htlcs.is_empty());
2775                         assert_eq!(update_fulfill_htlcs.len(), 1);
2776                         assert!(update_fail_malformed_htlcs.is_empty());
2777                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2778                 },
2779                 _ => panic!("Unexpected event"),
2780         };
2781         macro_rules! check_tx_local_broadcast {
2782                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2783                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2784                         assert_eq!(node_txn.len(), 3);
2785                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2786                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2787                         check_spends!(node_txn[1], $commitment_tx);
2788                         check_spends!(node_txn[2], $commitment_tx);
2789                         assert_ne!(node_txn[1].lock_time.0, 0);
2790                         assert_ne!(node_txn[2].lock_time.0, 0);
2791                         if $htlc_offered {
2792                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2793                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2794                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2795                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2796                         } else {
2797                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2798                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2799                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2800                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2801                         }
2802                         check_spends!(node_txn[0], $chan_tx);
2803                         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2804                         node_txn.clear();
2805                 } }
2806         }
2807         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2808         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2809         // timeout-claim of the output that nodes[2] just claimed via success.
2810         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
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() == 4 || node_txn.len() == 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2822         let commitment_spend =
2823                 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2824                         if node_txn.len() == 6 {
2825                                 // In some block `ConnectionStyle`s we may avoid broadcasting the double-spending
2826                                 // transactions spending the HTLC outputs of C's commitment transaction. Otherwise,
2827                                 // check that the extra broadcasts (double-)spend those here.
2828                                 check_spends!(node_txn[1], commitment_tx[0]);
2829                                 check_spends!(node_txn[2], commitment_tx[0]);
2830                                 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2831                         }
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         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2841         assert_eq!(commitment_spend.input.len(), 2);
2842         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2843         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2844         assert_eq!(commitment_spend.lock_time.0, 0);
2845         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2846         let funding_spend_offset = if node_txn.len() == 6 { 3 } else { 1 };
2847         check_spends!(node_txn[funding_spend_offset], chan_1.3);
2848         assert_eq!(node_txn[funding_spend_offset].input[0].witness.clone().last().unwrap().len(), 71);
2849         check_spends!(node_txn[funding_spend_offset + 1], node_txn[funding_spend_offset]);
2850         check_spends!(node_txn[funding_spend_offset + 2], node_txn[funding_spend_offset]);
2851         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2852         // we already checked the same situation with A.
2853
2854         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2855         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2856         connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2857         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2858         check_closed_broadcast!(nodes[0], true);
2859         check_added_monitors!(nodes[0], 1);
2860         let events = nodes[0].node.get_and_clear_pending_events();
2861         assert_eq!(events.len(), 5);
2862         let mut first_claimed = false;
2863         for event in events {
2864                 match event {
2865                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2866                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2867                                         assert!(!first_claimed);
2868                                         first_claimed = true;
2869                                 } else {
2870                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2871                                         assert_eq!(payment_hash, payment_hash_2);
2872                                 }
2873                         },
2874                         Event::PaymentPathSuccessful { .. } => {},
2875                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2876                         _ => panic!("Unexpected event"),
2877                 }
2878         }
2879         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2880 }
2881
2882 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2883         // Test that in case of a unilateral close onchain, we detect the state of output and
2884         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2885         // broadcasting the right event to other nodes in payment path.
2886         // A ------------------> B ----------------------> C (timeout)
2887         //    B's commitment tx                 C's commitment tx
2888         //            \                                  \
2889         //         B's HTLC timeout tx               B's timeout tx
2890
2891         let chanmon_cfgs = create_chanmon_cfgs(3);
2892         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2893         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2894         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2895         *nodes[0].connect_style.borrow_mut() = connect_style;
2896         *nodes[1].connect_style.borrow_mut() = connect_style;
2897         *nodes[2].connect_style.borrow_mut() = connect_style;
2898
2899         // Create some intial channels
2900         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2901         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2902
2903         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2904         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2905         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2906
2907         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2908
2909         // Broadcast legit commitment tx from C on B's chain
2910         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2911         check_spends!(commitment_tx[0], chan_2.3);
2912         nodes[2].node.fail_htlc_backwards(&payment_hash);
2913         check_added_monitors!(nodes[2], 0);
2914         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2915         check_added_monitors!(nodes[2], 1);
2916
2917         let events = nodes[2].node.get_and_clear_pending_msg_events();
2918         assert_eq!(events.len(), 1);
2919         match events[0] {
2920                 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, .. } } => {
2921                         assert!(update_add_htlcs.is_empty());
2922                         assert!(!update_fail_htlcs.is_empty());
2923                         assert!(update_fulfill_htlcs.is_empty());
2924                         assert!(update_fail_malformed_htlcs.is_empty());
2925                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2926                 },
2927                 _ => panic!("Unexpected event"),
2928         };
2929         mine_transaction(&nodes[2], &commitment_tx[0]);
2930         check_closed_broadcast!(nodes[2], true);
2931         check_added_monitors!(nodes[2], 1);
2932         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2933         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2934         assert_eq!(node_txn.len(), 1);
2935         check_spends!(node_txn[0], chan_2.3);
2936         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2937
2938         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2939         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2940         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2941         mine_transaction(&nodes[1], &commitment_tx[0]);
2942         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2943         let timeout_tx;
2944         {
2945                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2946                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2947                 assert_eq!(node_txn[0], node_txn[3]);
2948                 assert_eq!(node_txn[1], node_txn[4]);
2949
2950                 check_spends!(node_txn[2], commitment_tx[0]);
2951                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2952
2953                 check_spends!(node_txn[0], chan_2.3);
2954                 check_spends!(node_txn[1], node_txn[0]);
2955                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2956                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2957
2958                 timeout_tx = node_txn[2].clone();
2959                 node_txn.clear();
2960         }
2961
2962         mine_transaction(&nodes[1], &timeout_tx);
2963         check_added_monitors!(nodes[1], 1);
2964         check_closed_broadcast!(nodes[1], true);
2965
2966         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2967
2968         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 }]);
2969         check_added_monitors!(nodes[1], 1);
2970         let events = nodes[1].node.get_and_clear_pending_msg_events();
2971         assert_eq!(events.len(), 1);
2972         match events[0] {
2973                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
2974                         assert!(update_add_htlcs.is_empty());
2975                         assert!(!update_fail_htlcs.is_empty());
2976                         assert!(update_fulfill_htlcs.is_empty());
2977                         assert!(update_fail_malformed_htlcs.is_empty());
2978                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2979                 },
2980                 _ => panic!("Unexpected event"),
2981         };
2982
2983         // Broadcast legit commitment tx from B on A's chain
2984         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2985         check_spends!(commitment_tx[0], chan_1.3);
2986
2987         mine_transaction(&nodes[0], &commitment_tx[0]);
2988         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2989
2990         check_closed_broadcast!(nodes[0], true);
2991         check_added_monitors!(nodes[0], 1);
2992         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2993         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
2994         assert_eq!(node_txn.len(), 2);
2995         check_spends!(node_txn[0], chan_1.3);
2996         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2997         check_spends!(node_txn[1], commitment_tx[0]);
2998         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2999 }
3000
3001 #[test]
3002 fn test_htlc_on_chain_timeout() {
3003         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3004         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3005         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3006 }
3007
3008 #[test]
3009 fn test_simple_commitment_revoked_fail_backward() {
3010         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3011         // and fail backward accordingly.
3012
3013         let chanmon_cfgs = create_chanmon_cfgs(3);
3014         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3015         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3016         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3017
3018         // Create some initial channels
3019         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3020         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3021
3022         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3023         // Get the will-be-revoked local txn from nodes[2]
3024         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3025         // Revoke the old state
3026         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3027
3028         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3029
3030         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3031         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3032         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3033         check_added_monitors!(nodes[1], 1);
3034         check_closed_broadcast!(nodes[1], true);
3035
3036         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 }]);
3037         check_added_monitors!(nodes[1], 1);
3038         let events = nodes[1].node.get_and_clear_pending_msg_events();
3039         assert_eq!(events.len(), 1);
3040         match events[0] {
3041                 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, .. } } => {
3042                         assert!(update_add_htlcs.is_empty());
3043                         assert_eq!(update_fail_htlcs.len(), 1);
3044                         assert!(update_fulfill_htlcs.is_empty());
3045                         assert!(update_fail_malformed_htlcs.is_empty());
3046                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3047
3048                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3049                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3050                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3051                 },
3052                 _ => panic!("Unexpected event"),
3053         }
3054 }
3055
3056 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3057         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3058         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3059         // commitment transaction anymore.
3060         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3061         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3062         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3063         // technically disallowed and we should probably handle it reasonably.
3064         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3065         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3066         // transactions:
3067         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3068         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3069         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3070         //   and once they revoke the previous commitment transaction (allowing us to send a new
3071         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3072         let chanmon_cfgs = create_chanmon_cfgs(3);
3073         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3074         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3075         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3076
3077         // Create some initial channels
3078         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3079         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3080
3081         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 });
3082         // Get the will-be-revoked local txn from nodes[2]
3083         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3084         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3085         // Revoke the old state
3086         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3087
3088         let value = if use_dust {
3089                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3090                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3091                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3092         } else { 3000000 };
3093
3094         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3095         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3096         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3097
3098         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3099         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3100         check_added_monitors!(nodes[2], 1);
3101         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3102         assert!(updates.update_add_htlcs.is_empty());
3103         assert!(updates.update_fulfill_htlcs.is_empty());
3104         assert!(updates.update_fail_malformed_htlcs.is_empty());
3105         assert_eq!(updates.update_fail_htlcs.len(), 1);
3106         assert!(updates.update_fee.is_none());
3107         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3108         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3109         // Drop the last RAA from 3 -> 2
3110
3111         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3112         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3113         check_added_monitors!(nodes[2], 1);
3114         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3115         assert!(updates.update_add_htlcs.is_empty());
3116         assert!(updates.update_fulfill_htlcs.is_empty());
3117         assert!(updates.update_fail_malformed_htlcs.is_empty());
3118         assert_eq!(updates.update_fail_htlcs.len(), 1);
3119         assert!(updates.update_fee.is_none());
3120         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3121         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3122         check_added_monitors!(nodes[1], 1);
3123         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3124         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3125         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3126         check_added_monitors!(nodes[2], 1);
3127
3128         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3129         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3130         check_added_monitors!(nodes[2], 1);
3131         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3132         assert!(updates.update_add_htlcs.is_empty());
3133         assert!(updates.update_fulfill_htlcs.is_empty());
3134         assert!(updates.update_fail_malformed_htlcs.is_empty());
3135         assert_eq!(updates.update_fail_htlcs.len(), 1);
3136         assert!(updates.update_fee.is_none());
3137         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3138         // At this point first_payment_hash has dropped out of the latest two commitment
3139         // transactions that nodes[1] is tracking...
3140         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3141         check_added_monitors!(nodes[1], 1);
3142         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3143         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3144         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3145         check_added_monitors!(nodes[2], 1);
3146
3147         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3148         // on nodes[2]'s RAA.
3149         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3150         nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3151         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3152         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3153         check_added_monitors!(nodes[1], 0);
3154
3155         if deliver_bs_raa {
3156                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3157                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3158                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3159                 check_added_monitors!(nodes[1], 1);
3160                 let events = nodes[1].node.get_and_clear_pending_events();
3161                 assert_eq!(events.len(), 2);
3162                 match events[0] {
3163                         Event::PendingHTLCsForwardable { .. } => { },
3164                         _ => panic!("Unexpected event"),
3165                 };
3166                 match events[1] {
3167                         Event::HTLCHandlingFailed { .. } => { },
3168                         _ => panic!("Unexpected event"),
3169                 }
3170                 // Deliberately don't process the pending fail-back so they all fail back at once after
3171                 // block connection just like the !deliver_bs_raa case
3172         }
3173
3174         let mut failed_htlcs = HashSet::new();
3175         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3176
3177         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3178         check_added_monitors!(nodes[1], 1);
3179         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3180
3181         let events = nodes[1].node.get_and_clear_pending_events();
3182         assert_eq!(events.len(), if deliver_bs_raa { 2 + nodes.len() - 1 } else { 3 + nodes.len() });
3183         match events[0] {
3184                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3185                 _ => panic!("Unexepected event"),
3186         }
3187         match events[1] {
3188                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3189                         assert_eq!(*payment_hash, fourth_payment_hash);
3190                 },
3191                 _ => panic!("Unexpected event"),
3192         }
3193         if !deliver_bs_raa {
3194                 match events[2] {
3195                         Event::PendingHTLCsForwardable { .. } => { },
3196                         _ => panic!("Unexpected event"),
3197                 };
3198                 nodes[1].node.abandon_payment(PaymentId(fourth_payment_hash.0));
3199                 let payment_failed_events = nodes[1].node.get_and_clear_pending_events();
3200                 assert_eq!(payment_failed_events.len(), 1);
3201                 match payment_failed_events[0] {
3202                         Event::PaymentFailed { ref payment_hash, .. } => {
3203                                 assert_eq!(*payment_hash, fourth_payment_hash);
3204                         },
3205                         _ => panic!("Unexpected event"),
3206                 }
3207         }
3208         nodes[1].node.process_pending_htlc_forwards();
3209         check_added_monitors!(nodes[1], 1);
3210
3211         let events = nodes[1].node.get_and_clear_pending_msg_events();
3212         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3213         match events[if deliver_bs_raa { 1 } else { 0 }] {
3214                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3215                 _ => panic!("Unexpected event"),
3216         }
3217         match events[if deliver_bs_raa { 2 } else { 1 }] {
3218                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3219                         assert_eq!(channel_id, chan_2.2);
3220                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3221                 },
3222                 _ => panic!("Unexpected event"),
3223         }
3224         if deliver_bs_raa {
3225                 match events[0] {
3226                         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, .. } } => {
3227                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3228                                 assert_eq!(update_add_htlcs.len(), 1);
3229                                 assert!(update_fulfill_htlcs.is_empty());
3230                                 assert!(update_fail_htlcs.is_empty());
3231                                 assert!(update_fail_malformed_htlcs.is_empty());
3232                         },
3233                         _ => panic!("Unexpected event"),
3234                 }
3235         }
3236         match events[if deliver_bs_raa { 3 } else { 2 }] {
3237                 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, .. } } => {
3238                         assert!(update_add_htlcs.is_empty());
3239                         assert_eq!(update_fail_htlcs.len(), 3);
3240                         assert!(update_fulfill_htlcs.is_empty());
3241                         assert!(update_fail_malformed_htlcs.is_empty());
3242                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3243
3244                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3245                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3246                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3247
3248                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3249
3250                         let events = nodes[0].node.get_and_clear_pending_events();
3251                         assert_eq!(events.len(), 3);
3252                         match events[0] {
3253                                 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3254                                         assert!(failed_htlcs.insert(payment_hash.0));
3255                                         // If we delivered B's RAA we got an unknown preimage error, not something
3256                                         // that we should update our routing table for.
3257                                         if !deliver_bs_raa {
3258                                                 assert!(network_update.is_some());
3259                                         }
3260                                 },
3261                                 _ => panic!("Unexpected event"),
3262                         }
3263                         match events[1] {
3264                                 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3265                                         assert!(failed_htlcs.insert(payment_hash.0));
3266                                         assert!(network_update.is_some());
3267                                 },
3268                                 _ => panic!("Unexpected event"),
3269                         }
3270                         match events[2] {
3271                                 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3272                                         assert!(failed_htlcs.insert(payment_hash.0));
3273                                         assert!(network_update.is_some());
3274                                 },
3275                                 _ => panic!("Unexpected event"),
3276                         }
3277                 },
3278                 _ => panic!("Unexpected event"),
3279         }
3280
3281         assert!(failed_htlcs.contains(&first_payment_hash.0));
3282         assert!(failed_htlcs.contains(&second_payment_hash.0));
3283         assert!(failed_htlcs.contains(&third_payment_hash.0));
3284 }
3285
3286 #[test]
3287 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3288         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3289         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3290         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3291         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3292 }
3293
3294 #[test]
3295 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3296         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3297         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3298         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3299         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3300 }
3301
3302 #[test]
3303 fn fail_backward_pending_htlc_upon_channel_failure() {
3304         let chanmon_cfgs = create_chanmon_cfgs(2);
3305         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3306         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3307         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3308         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3309
3310         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3311         {
3312                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3313                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
3314                 check_added_monitors!(nodes[0], 1);
3315
3316                 let payment_event = {
3317                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3318                         assert_eq!(events.len(), 1);
3319                         SendEvent::from_event(events.remove(0))
3320                 };
3321                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3322                 assert_eq!(payment_event.msgs.len(), 1);
3323         }
3324
3325         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3326         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3327         {
3328                 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3329                 check_added_monitors!(nodes[0], 0);
3330
3331                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3332         }
3333
3334         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3335         {
3336                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3337
3338                 let secp_ctx = Secp256k1::new();
3339                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3340                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3341                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3342                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3343                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3344
3345                 // Send a 0-msat update_add_htlc to fail the channel.
3346                 let update_add_htlc = msgs::UpdateAddHTLC {
3347                         channel_id: chan.2,
3348                         htlc_id: 0,
3349                         amount_msat: 0,
3350                         payment_hash,
3351                         cltv_expiry,
3352                         onion_routing_packet,
3353                 };
3354                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3355         }
3356         let events = nodes[0].node.get_and_clear_pending_events();
3357         assert_eq!(events.len(), 2);
3358         // Check that Alice fails backward the pending HTLC from the second payment.
3359         match events[0] {
3360                 Event::PaymentPathFailed { payment_hash, .. } => {
3361                         assert_eq!(payment_hash, failed_payment_hash);
3362                 },
3363                 _ => panic!("Unexpected event"),
3364         }
3365         match events[1] {
3366                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3367                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3368                 },
3369                 _ => panic!("Unexpected event {:?}", events[1]),
3370         }
3371         check_closed_broadcast!(nodes[0], true);
3372         check_added_monitors!(nodes[0], 1);
3373 }
3374
3375 #[test]
3376 fn test_htlc_ignore_latest_remote_commitment() {
3377         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3378         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3379         let chanmon_cfgs = create_chanmon_cfgs(2);
3380         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3381         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3382         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3383         if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3384                 // We rely on the ability to connect a block redundantly, which isn't allowed via
3385                 // `chain::Listen`, so we never run the test if we randomly get assigned that
3386                 // connect_style.
3387                 return;
3388         }
3389         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3390
3391         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3392         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3393         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3394         check_closed_broadcast!(nodes[0], true);
3395         check_added_monitors!(nodes[0], 1);
3396         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3397
3398         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3399         assert_eq!(node_txn.len(), 3);
3400         assert_eq!(node_txn[0], node_txn[1]);
3401
3402         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
3403         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3404         check_closed_broadcast!(nodes[1], true);
3405         check_added_monitors!(nodes[1], 1);
3406         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3407
3408         // Duplicate the connect_block call since this may happen due to other listeners
3409         // registering new transactions
3410         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3411 }
3412
3413 #[test]
3414 fn test_force_close_fail_back() {
3415         // Check which HTLCs are failed-backwards on channel force-closure
3416         let chanmon_cfgs = create_chanmon_cfgs(3);
3417         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3418         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3419         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3420         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3421         create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3422
3423         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3424
3425         let mut payment_event = {
3426                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3427                 check_added_monitors!(nodes[0], 1);
3428
3429                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3430                 assert_eq!(events.len(), 1);
3431                 SendEvent::from_event(events.remove(0))
3432         };
3433
3434         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3435         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3436
3437         expect_pending_htlcs_forwardable!(nodes[1]);
3438
3439         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3440         assert_eq!(events_2.len(), 1);
3441         payment_event = SendEvent::from_event(events_2.remove(0));
3442         assert_eq!(payment_event.msgs.len(), 1);
3443
3444         check_added_monitors!(nodes[1], 1);
3445         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3446         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3447         check_added_monitors!(nodes[2], 1);
3448         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3449
3450         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3451         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3452         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3453
3454         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3455         check_closed_broadcast!(nodes[2], true);
3456         check_added_monitors!(nodes[2], 1);
3457         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3458         let tx = {
3459                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3460                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3461                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3462                 // back to nodes[1] upon timeout otherwise.
3463                 assert_eq!(node_txn.len(), 1);
3464                 node_txn.remove(0)
3465         };
3466
3467         mine_transaction(&nodes[1], &tx);
3468
3469         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3470         check_closed_broadcast!(nodes[1], true);
3471         check_added_monitors!(nodes[1], 1);
3472         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3473
3474         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3475         {
3476                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3477                         .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);
3478         }
3479         mine_transaction(&nodes[2], &tx);
3480         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3481         assert_eq!(node_txn.len(), 1);
3482         assert_eq!(node_txn[0].input.len(), 1);
3483         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3484         assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3485         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3486
3487         check_spends!(node_txn[0], tx);
3488 }
3489
3490 #[test]
3491 fn test_dup_events_on_peer_disconnect() {
3492         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3493         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3494         // as we used to generate the event immediately upon receipt of the payment preimage in the
3495         // update_fulfill_htlc message.
3496
3497         let chanmon_cfgs = create_chanmon_cfgs(2);
3498         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3499         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3500         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3501         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3502
3503         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3504
3505         nodes[1].node.claim_funds(payment_preimage);
3506         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3507         check_added_monitors!(nodes[1], 1);
3508         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3509         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3510         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3511
3512         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3513         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3514
3515         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3516         expect_payment_path_successful!(nodes[0]);
3517 }
3518
3519 #[test]
3520 fn test_peer_disconnected_before_funding_broadcasted() {
3521         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3522         // before the funding transaction has been broadcasted.
3523         let chanmon_cfgs = create_chanmon_cfgs(2);
3524         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3525         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3526         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3527
3528         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3529         // broadcasted, even though it's created by `nodes[0]`.
3530         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();
3531         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3532         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
3533         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3534         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
3535
3536         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3537         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3538
3539         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3540
3541         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3542         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3543
3544         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3545         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3546         // broadcasted.
3547         {
3548                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3549         }
3550
3551         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3552         // disconnected before the funding transaction was broadcasted.
3553         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3554         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3555
3556         check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3557         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3558 }
3559
3560 #[test]
3561 fn test_simple_peer_disconnect() {
3562         // Test that we can reconnect when there are no lost messages
3563         let chanmon_cfgs = create_chanmon_cfgs(3);
3564         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3565         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3566         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3567         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3568         create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3569
3570         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3571         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3572         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3573
3574         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3575         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3576         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3577         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3578
3579         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3580         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3581         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3582
3583         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3584         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3585         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3586         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3587
3588         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3589         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3590
3591         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3592         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3593
3594         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3595         {
3596                 let events = nodes[0].node.get_and_clear_pending_events();
3597                 assert_eq!(events.len(), 3);
3598                 match events[0] {
3599                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3600                                 assert_eq!(payment_preimage, payment_preimage_3);
3601                                 assert_eq!(payment_hash, payment_hash_3);
3602                         },
3603                         _ => panic!("Unexpected event"),
3604                 }
3605                 match events[1] {
3606                         Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3607                                 assert_eq!(payment_hash, payment_hash_5);
3608                                 assert!(payment_failed_permanently);
3609                         },
3610                         _ => panic!("Unexpected event"),
3611                 }
3612                 match events[2] {
3613                         Event::PaymentPathSuccessful { .. } => {},
3614                         _ => panic!("Unexpected event"),
3615                 }
3616         }
3617
3618         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3619         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3620 }
3621
3622 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3623         // Test that we can reconnect when in-flight HTLC updates get dropped
3624         let chanmon_cfgs = create_chanmon_cfgs(2);
3625         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3626         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3627         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3628
3629         let mut as_channel_ready = None;
3630         let channel_id = if messages_delivered == 0 {
3631                 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3632                 as_channel_ready = Some(channel_ready);
3633                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3634                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3635                 // it before the channel_reestablish message.
3636                 chan_id
3637         } else {
3638                 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2
3639         };
3640
3641         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3642
3643         let payment_event = {
3644                 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3645                 check_added_monitors!(nodes[0], 1);
3646
3647                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3648                 assert_eq!(events.len(), 1);
3649                 SendEvent::from_event(events.remove(0))
3650         };
3651         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3652
3653         if messages_delivered < 2 {
3654                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3655         } else {
3656                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3657                 if messages_delivered >= 3 {
3658                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3659                         check_added_monitors!(nodes[1], 1);
3660                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3661
3662                         if messages_delivered >= 4 {
3663                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3664                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3665                                 check_added_monitors!(nodes[0], 1);
3666
3667                                 if messages_delivered >= 5 {
3668                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3669                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3670                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3671                                         check_added_monitors!(nodes[0], 1);
3672
3673                                         if messages_delivered >= 6 {
3674                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3675                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3676                                                 check_added_monitors!(nodes[1], 1);
3677                                         }
3678                                 }
3679                         }
3680                 }
3681         }
3682
3683         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3684         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3685         if messages_delivered < 3 {
3686                 if simulate_broken_lnd {
3687                         // lnd has a long-standing bug where they send a channel_ready prior to a
3688                         // channel_reestablish if you reconnect prior to channel_ready time.
3689                         //
3690                         // Here we simulate that behavior, delivering a channel_ready immediately on
3691                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3692                         // in `reconnect_nodes` but we currently don't fail based on that.
3693                         //
3694                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3695                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3696                 }
3697                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3698                 // received on either side, both sides will need to resend them.
3699                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3700         } else if messages_delivered == 3 {
3701                 // nodes[0] still wants its RAA + commitment_signed
3702                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3703         } else if messages_delivered == 4 {
3704                 // nodes[0] still wants its commitment_signed
3705                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3706         } else if messages_delivered == 5 {
3707                 // nodes[1] still wants its final RAA
3708                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3709         } else if messages_delivered == 6 {
3710                 // Everything was delivered...
3711                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3712         }
3713
3714         let events_1 = nodes[1].node.get_and_clear_pending_events();
3715         if messages_delivered == 0 {
3716                 assert_eq!(events_1.len(), 2);
3717                 match events_1[0] {
3718                         Event::ChannelReady { .. } => { },
3719                         _ => panic!("Unexpected event"),
3720                 };
3721                 match events_1[1] {
3722                         Event::PendingHTLCsForwardable { .. } => { },
3723                         _ => panic!("Unexpected event"),
3724                 };
3725         } else {
3726                 assert_eq!(events_1.len(), 1);
3727                 match events_1[0] {
3728                         Event::PendingHTLCsForwardable { .. } => { },
3729                         _ => panic!("Unexpected event"),
3730                 };
3731         }
3732
3733         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3734         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3735         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3736
3737         nodes[1].node.process_pending_htlc_forwards();
3738
3739         let events_2 = nodes[1].node.get_and_clear_pending_events();
3740         assert_eq!(events_2.len(), 1);
3741         match events_2[0] {
3742                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
3743                         assert_eq!(payment_hash_1, *payment_hash);
3744                         assert_eq!(amount_msat, 1_000_000);
3745                         assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3746                         assert_eq!(via_channel_id, Some(channel_id));
3747                         match &purpose {
3748                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3749                                         assert!(payment_preimage.is_none());
3750                                         assert_eq!(payment_secret_1, *payment_secret);
3751                                 },
3752                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3753                         }
3754                 },
3755                 _ => panic!("Unexpected event"),
3756         }
3757
3758         nodes[1].node.claim_funds(payment_preimage_1);
3759         check_added_monitors!(nodes[1], 1);
3760         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3761
3762         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3763         assert_eq!(events_3.len(), 1);
3764         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3765                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3766                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3767                         assert!(updates.update_add_htlcs.is_empty());
3768                         assert!(updates.update_fail_htlcs.is_empty());
3769                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3770                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3771                         assert!(updates.update_fee.is_none());
3772                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3773                 },
3774                 _ => panic!("Unexpected event"),
3775         };
3776
3777         if messages_delivered >= 1 {
3778                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3779
3780                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3781                 assert_eq!(events_4.len(), 1);
3782                 match events_4[0] {
3783                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3784                                 assert_eq!(payment_preimage_1, *payment_preimage);
3785                                 assert_eq!(payment_hash_1, *payment_hash);
3786                         },
3787                         _ => panic!("Unexpected event"),
3788                 }
3789
3790                 if messages_delivered >= 2 {
3791                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3792                         check_added_monitors!(nodes[0], 1);
3793                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3794
3795                         if messages_delivered >= 3 {
3796                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3797                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3798                                 check_added_monitors!(nodes[1], 1);
3799
3800                                 if messages_delivered >= 4 {
3801                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3802                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3803                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3804                                         check_added_monitors!(nodes[1], 1);
3805
3806                                         if messages_delivered >= 5 {
3807                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3808                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3809                                                 check_added_monitors!(nodes[0], 1);
3810                                         }
3811                                 }
3812                         }
3813                 }
3814         }
3815
3816         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3817         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3818         if messages_delivered < 2 {
3819                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3820                 if messages_delivered < 1 {
3821                         expect_payment_sent!(nodes[0], payment_preimage_1);
3822                 } else {
3823                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3824                 }
3825         } else if messages_delivered == 2 {
3826                 // nodes[0] still wants its RAA + commitment_signed
3827                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3828         } else if messages_delivered == 3 {
3829                 // nodes[0] still wants its commitment_signed
3830                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3831         } else if messages_delivered == 4 {
3832                 // nodes[1] still wants its final RAA
3833                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3834         } else if messages_delivered == 5 {
3835                 // Everything was delivered...
3836                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3837         }
3838
3839         if messages_delivered == 1 || messages_delivered == 2 {
3840                 expect_payment_path_successful!(nodes[0]);
3841         }
3842
3843         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3844         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3845         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3846
3847         if messages_delivered > 2 {
3848                 expect_payment_path_successful!(nodes[0]);
3849         }
3850
3851         // Channel should still work fine...
3852         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3853         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3854         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3855 }
3856
3857 #[test]
3858 fn test_drop_messages_peer_disconnect_a() {
3859         do_test_drop_messages_peer_disconnect(0, true);
3860         do_test_drop_messages_peer_disconnect(0, false);
3861         do_test_drop_messages_peer_disconnect(1, false);
3862         do_test_drop_messages_peer_disconnect(2, false);
3863 }
3864
3865 #[test]
3866 fn test_drop_messages_peer_disconnect_b() {
3867         do_test_drop_messages_peer_disconnect(3, false);
3868         do_test_drop_messages_peer_disconnect(4, false);
3869         do_test_drop_messages_peer_disconnect(5, false);
3870         do_test_drop_messages_peer_disconnect(6, false);
3871 }
3872
3873 #[test]
3874 fn test_channel_ready_without_best_block_updated() {
3875         // Previously, if we were offline when a funding transaction was locked in, and then we came
3876         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3877         // generate a channel_ready until a later best_block_updated. This tests that we generate the
3878         // channel_ready immediately instead.
3879         let chanmon_cfgs = create_chanmon_cfgs(2);
3880         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3881         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3882         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3883         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3884
3885         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3886
3887         let conf_height = nodes[0].best_block_info().1 + 1;
3888         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3889         let block_txn = [funding_tx];
3890         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3891         let conf_block_header = nodes[0].get_block_header(conf_height);
3892         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3893
3894         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
3895         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
3896         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3897 }
3898
3899 #[test]
3900 fn test_drop_messages_peer_disconnect_dual_htlc() {
3901         // Test that we can handle reconnecting when both sides of a channel have pending
3902         // commitment_updates when we disconnect.
3903         let chanmon_cfgs = create_chanmon_cfgs(2);
3904         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3905         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3906         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3907         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3908
3909         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3910
3911         // Now try to send a second payment which will fail to send
3912         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3913         nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
3914         check_added_monitors!(nodes[0], 1);
3915
3916         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3917         assert_eq!(events_1.len(), 1);
3918         match events_1[0] {
3919                 MessageSendEvent::UpdateHTLCs { .. } => {},
3920                 _ => panic!("Unexpected event"),
3921         }
3922
3923         nodes[1].node.claim_funds(payment_preimage_1);
3924         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3925         check_added_monitors!(nodes[1], 1);
3926
3927         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3928         assert_eq!(events_2.len(), 1);
3929         match events_2[0] {
3930                 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 } } => {
3931                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3932                         assert!(update_add_htlcs.is_empty());
3933                         assert_eq!(update_fulfill_htlcs.len(), 1);
3934                         assert!(update_fail_htlcs.is_empty());
3935                         assert!(update_fail_malformed_htlcs.is_empty());
3936                         assert!(update_fee.is_none());
3937
3938                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3939                         let events_3 = nodes[0].node.get_and_clear_pending_events();
3940                         assert_eq!(events_3.len(), 1);
3941                         match events_3[0] {
3942                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3943                                         assert_eq!(*payment_preimage, payment_preimage_1);
3944                                         assert_eq!(*payment_hash, payment_hash_1);
3945                                 },
3946                                 _ => panic!("Unexpected event"),
3947                         }
3948
3949                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3950                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3951                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3952                         check_added_monitors!(nodes[0], 1);
3953                 },
3954                 _ => panic!("Unexpected event"),
3955         }
3956
3957         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3958         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3959
3960         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
3961         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3962         assert_eq!(reestablish_1.len(), 1);
3963         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
3964         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3965         assert_eq!(reestablish_2.len(), 1);
3966
3967         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3968         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3969         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3970         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3971
3972         assert!(as_resp.0.is_none());
3973         assert!(bs_resp.0.is_none());
3974
3975         assert!(bs_resp.1.is_none());
3976         assert!(bs_resp.2.is_none());
3977
3978         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3979
3980         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3981         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3982         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3983         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3984         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3985         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3986         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3987         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3988         // No commitment_signed so get_event_msg's assert(len == 1) passes
3989         check_added_monitors!(nodes[1], 1);
3990
3991         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3992         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3993         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3994         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3995         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3996         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3997         assert!(bs_second_commitment_signed.update_fee.is_none());
3998         check_added_monitors!(nodes[1], 1);
3999
4000         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4001         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4002         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4003         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4004         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4005         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4006         assert!(as_commitment_signed.update_fee.is_none());
4007         check_added_monitors!(nodes[0], 1);
4008
4009         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4010         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4011         // No commitment_signed so get_event_msg's assert(len == 1) passes
4012         check_added_monitors!(nodes[0], 1);
4013
4014         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4015         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4016         // No commitment_signed so get_event_msg's assert(len == 1) passes
4017         check_added_monitors!(nodes[1], 1);
4018
4019         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4020         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4021         check_added_monitors!(nodes[1], 1);
4022
4023         expect_pending_htlcs_forwardable!(nodes[1]);
4024
4025         let events_5 = nodes[1].node.get_and_clear_pending_events();
4026         assert_eq!(events_5.len(), 1);
4027         match events_5[0] {
4028                 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4029                         assert_eq!(payment_hash_2, *payment_hash);
4030                         match &purpose {
4031                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4032                                         assert!(payment_preimage.is_none());
4033                                         assert_eq!(payment_secret_2, *payment_secret);
4034                                 },
4035                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4036                         }
4037                 },
4038                 _ => panic!("Unexpected event"),
4039         }
4040
4041         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4042         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4043         check_added_monitors!(nodes[0], 1);
4044
4045         expect_payment_path_successful!(nodes[0]);
4046         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4047 }
4048
4049 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4050         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4051         // to avoid our counterparty failing the channel.
4052         let chanmon_cfgs = create_chanmon_cfgs(2);
4053         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4054         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4055         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4056
4057         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4058
4059         let our_payment_hash = if send_partial_mpp {
4060                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4061                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4062                 // indicates there are more HTLCs coming.
4063                 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.
4064                 let payment_id = PaymentId([42; 32]);
4065                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(payment_secret), payment_id, &route).unwrap();
4066                 nodes[0].node.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();
4067                 check_added_monitors!(nodes[0], 1);
4068                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4069                 assert_eq!(events.len(), 1);
4070                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4071                 // hop should *not* yet generate any PaymentClaimable event(s).
4072                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4073                 our_payment_hash
4074         } else {
4075                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4076         };
4077
4078         let mut block = Block {
4079                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
4080                 txdata: vec![],
4081         };
4082         connect_block(&nodes[0], &block);
4083         connect_block(&nodes[1], &block);
4084         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4085         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4086                 block.header.prev_blockhash = block.block_hash();
4087                 connect_block(&nodes[0], &block);
4088                 connect_block(&nodes[1], &block);
4089         }
4090
4091         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4092
4093         check_added_monitors!(nodes[1], 1);
4094         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4095         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4096         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4097         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4098         assert!(htlc_timeout_updates.update_fee.is_none());
4099
4100         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4101         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4102         // 100_000 msat as u64, followed by the height at which we failed back above
4103         let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4104         expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4105         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4106 }
4107
4108 #[test]
4109 fn test_htlc_timeout() {
4110         do_test_htlc_timeout(true);
4111         do_test_htlc_timeout(false);
4112 }
4113
4114 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4115         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4116         let chanmon_cfgs = create_chanmon_cfgs(3);
4117         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4118         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4119         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4120         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4121         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4122
4123         // Make sure all nodes are at the same starting height
4124         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4125         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4126         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4127
4128         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4129         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4130         {
4131                 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4132         }
4133         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4134         check_added_monitors!(nodes[1], 1);
4135
4136         // Now attempt to route a second payment, which should be placed in the holding cell
4137         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4138         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4139         sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4140         if forwarded_htlc {
4141                 check_added_monitors!(nodes[0], 1);
4142                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4143                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4144                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4145                 expect_pending_htlcs_forwardable!(nodes[1]);
4146         }
4147         check_added_monitors!(nodes[1], 0);
4148
4149         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4150         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4151         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4152         connect_blocks(&nodes[1], 1);
4153
4154         if forwarded_htlc {
4155                 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 }]);
4156                 check_added_monitors!(nodes[1], 1);
4157                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4158                 assert_eq!(fail_commit.len(), 1);
4159                 match fail_commit[0] {
4160                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4161                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4162                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4163                         },
4164                         _ => unreachable!(),
4165                 }
4166                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4167         } else {
4168                 expect_payment_failed!(nodes[1], second_payment_hash, false);
4169         }
4170 }
4171
4172 #[test]
4173 fn test_holding_cell_htlc_add_timeouts() {
4174         do_test_holding_cell_htlc_add_timeouts(false);
4175         do_test_holding_cell_htlc_add_timeouts(true);
4176 }
4177
4178 macro_rules! check_spendable_outputs {
4179         ($node: expr, $keysinterface: expr) => {
4180                 {
4181                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4182                         let mut txn = Vec::new();
4183                         let mut all_outputs = Vec::new();
4184                         let secp_ctx = Secp256k1::new();
4185                         for event in events.drain(..) {
4186                                 match event {
4187                                         Event::SpendableOutputs { mut outputs } => {
4188                                                 for outp in outputs.drain(..) {
4189                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4190                                                         all_outputs.push(outp);
4191                                                 }
4192                                         },
4193                                         _ => panic!("Unexpected event"),
4194                                 };
4195                         }
4196                         if all_outputs.len() > 1 {
4197                                 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) {
4198                                         txn.push(tx);
4199                                 }
4200                         }
4201                         txn
4202                 }
4203         }
4204 }
4205
4206 #[test]
4207 fn test_claim_sizeable_push_msat() {
4208         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4209         let chanmon_cfgs = create_chanmon_cfgs(2);
4210         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4211         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4212         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4213
4214         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4215         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4216         check_closed_broadcast!(nodes[1], true);
4217         check_added_monitors!(nodes[1], 1);
4218         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4219         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4220         assert_eq!(node_txn.len(), 1);
4221         check_spends!(node_txn[0], chan.3);
4222         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
4223
4224         mine_transaction(&nodes[1], &node_txn[0]);
4225         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4226
4227         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4228         assert_eq!(spend_txn.len(), 1);
4229         assert_eq!(spend_txn[0].input.len(), 1);
4230         check_spends!(spend_txn[0], node_txn[0]);
4231         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4232 }
4233
4234 #[test]
4235 fn test_claim_on_remote_sizeable_push_msat() {
4236         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4237         // to_remote output is encumbered by a P2WPKH
4238         let chanmon_cfgs = create_chanmon_cfgs(2);
4239         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4240         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4241         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4242
4243         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4244         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4245         check_closed_broadcast!(nodes[0], true);
4246         check_added_monitors!(nodes[0], 1);
4247         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4248
4249         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4250         assert_eq!(node_txn.len(), 1);
4251         check_spends!(node_txn[0], chan.3);
4252         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
4253
4254         mine_transaction(&nodes[1], &node_txn[0]);
4255         check_closed_broadcast!(nodes[1], true);
4256         check_added_monitors!(nodes[1], 1);
4257         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4258         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4259
4260         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4261         assert_eq!(spend_txn.len(), 1);
4262         check_spends!(spend_txn[0], node_txn[0]);
4263 }
4264
4265 #[test]
4266 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4267         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4268         // to_remote output is encumbered by a P2WPKH
4269
4270         let chanmon_cfgs = create_chanmon_cfgs(2);
4271         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4272         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4273         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4274
4275         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4276         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4277         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4278         assert_eq!(revoked_local_txn[0].input.len(), 1);
4279         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4280
4281         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4282         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4283         check_closed_broadcast!(nodes[1], true);
4284         check_added_monitors!(nodes[1], 1);
4285         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4286
4287         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4288         mine_transaction(&nodes[1], &node_txn[0]);
4289         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4290
4291         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4292         assert_eq!(spend_txn.len(), 3);
4293         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4294         check_spends!(spend_txn[1], node_txn[0]);
4295         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4296 }
4297
4298 #[test]
4299 fn test_static_spendable_outputs_preimage_tx() {
4300         let chanmon_cfgs = create_chanmon_cfgs(2);
4301         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4302         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4303         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4304
4305         // Create some initial channels
4306         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4307
4308         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4309
4310         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4311         assert_eq!(commitment_tx[0].input.len(), 1);
4312         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4313
4314         // Settle A's commitment tx on B's chain
4315         nodes[1].node.claim_funds(payment_preimage);
4316         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4317         check_added_monitors!(nodes[1], 1);
4318         mine_transaction(&nodes[1], &commitment_tx[0]);
4319         check_added_monitors!(nodes[1], 1);
4320         let events = nodes[1].node.get_and_clear_pending_msg_events();
4321         match events[0] {
4322                 MessageSendEvent::UpdateHTLCs { .. } => {},
4323                 _ => panic!("Unexpected event"),
4324         }
4325         match events[1] {
4326                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4327                 _ => panic!("Unexepected event"),
4328         }
4329
4330         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4331         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4332         assert_eq!(node_txn.len(), 3);
4333         check_spends!(node_txn[0], commitment_tx[0]);
4334         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4335         check_spends!(node_txn[1], chan_1.3);
4336         check_spends!(node_txn[2], node_txn[1]);
4337
4338         mine_transaction(&nodes[1], &node_txn[0]);
4339         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4340         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4341
4342         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4343         assert_eq!(spend_txn.len(), 1);
4344         check_spends!(spend_txn[0], node_txn[0]);
4345 }
4346
4347 #[test]
4348 fn test_static_spendable_outputs_timeout_tx() {
4349         let chanmon_cfgs = create_chanmon_cfgs(2);
4350         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4351         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4352         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4353
4354         // Create some initial channels
4355         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4356
4357         // Rebalance the network a bit by relaying one payment through all the channels ...
4358         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4359
4360         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4361
4362         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4363         assert_eq!(commitment_tx[0].input.len(), 1);
4364         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4365
4366         // Settle A's commitment tx on B' chain
4367         mine_transaction(&nodes[1], &commitment_tx[0]);
4368         check_added_monitors!(nodes[1], 1);
4369         let events = nodes[1].node.get_and_clear_pending_msg_events();
4370         match events[0] {
4371                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4372                 _ => panic!("Unexpected event"),
4373         }
4374         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4375
4376         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4377         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4378         assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4379         check_spends!(node_txn[0], chan_1.3.clone());
4380         check_spends!(node_txn[1],  commitment_tx[0].clone());
4381         assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4382
4383         mine_transaction(&nodes[1], &node_txn[1]);
4384         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4385         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4386         expect_payment_failed!(nodes[1], our_payment_hash, false);
4387
4388         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4389         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4390         check_spends!(spend_txn[0], commitment_tx[0]);
4391         check_spends!(spend_txn[1], node_txn[1]);
4392         check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4393 }
4394
4395 #[test]
4396 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4397         let chanmon_cfgs = create_chanmon_cfgs(2);
4398         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4399         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4400         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4401
4402         // Create some initial channels
4403         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4404
4405         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4406         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4407         assert_eq!(revoked_local_txn[0].input.len(), 1);
4408         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4409
4410         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4411
4412         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4413         check_closed_broadcast!(nodes[1], true);
4414         check_added_monitors!(nodes[1], 1);
4415         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4416
4417         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4418         assert_eq!(node_txn.len(), 2);
4419         assert_eq!(node_txn[0].input.len(), 2);
4420         check_spends!(node_txn[0], revoked_local_txn[0]);
4421
4422         mine_transaction(&nodes[1], &node_txn[0]);
4423         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4424
4425         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4426         assert_eq!(spend_txn.len(), 1);
4427         check_spends!(spend_txn[0], node_txn[0]);
4428 }
4429
4430 #[test]
4431 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4432         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4433         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4434         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4435         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4436         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4437
4438         // Create some initial channels
4439         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4440
4441         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4442         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4443         assert_eq!(revoked_local_txn[0].input.len(), 1);
4444         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4445
4446         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4447
4448         // A will generate HTLC-Timeout from revoked commitment tx
4449         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4450         check_closed_broadcast!(nodes[0], true);
4451         check_added_monitors!(nodes[0], 1);
4452         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4453         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4454
4455         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4456         assert_eq!(revoked_htlc_txn.len(), 2);
4457         check_spends!(revoked_htlc_txn[0], chan_1.3);
4458         assert_eq!(revoked_htlc_txn[1].input.len(), 1);
4459         assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4460         check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
4461         assert_ne!(revoked_htlc_txn[1].lock_time.0, 0); // HTLC-Timeout
4462
4463         // B will generate justice tx from A's revoked commitment/HTLC tx
4464         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4465         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
4466         check_closed_broadcast!(nodes[1], true);
4467         check_added_monitors!(nodes[1], 1);
4468         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4469
4470         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4471         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4472         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4473         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4474         // transactions next...
4475         assert_eq!(node_txn[0].input.len(), 3);
4476         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
4477
4478         assert_eq!(node_txn[1].input.len(), 2);
4479         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
4480         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
4481                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4482         } else {
4483                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
4484                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4485         }
4486
4487         assert_eq!(node_txn[2].input.len(), 1);
4488         check_spends!(node_txn[2], chan_1.3);
4489
4490         mine_transaction(&nodes[1], &node_txn[1]);
4491         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4492
4493         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4494         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4495         assert_eq!(spend_txn.len(), 1);
4496         assert_eq!(spend_txn[0].input.len(), 1);
4497         check_spends!(spend_txn[0], node_txn[1]);
4498 }
4499
4500 #[test]
4501 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4502         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4503         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4504         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4505         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4506         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4507
4508         // Create some initial channels
4509         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4510
4511         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4512         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4513         assert_eq!(revoked_local_txn[0].input.len(), 1);
4514         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4515
4516         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4517         assert_eq!(revoked_local_txn[0].output.len(), 2);
4518
4519         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4520
4521         // B will generate HTLC-Success from revoked commitment tx
4522         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4523         check_closed_broadcast!(nodes[1], true);
4524         check_added_monitors!(nodes[1], 1);
4525         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4526         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4527
4528         assert_eq!(revoked_htlc_txn.len(), 2);
4529         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4530         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4531         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4532
4533         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4534         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4535         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4536
4537         // A will generate justice tx from B's revoked commitment/HTLC tx
4538         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4539         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4540         check_closed_broadcast!(nodes[0], true);
4541         check_added_monitors!(nodes[0], 1);
4542         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4543
4544         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4545         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
4546
4547         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4548         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4549         // transactions next...
4550         assert_eq!(node_txn[0].input.len(), 2);
4551         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4552         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4553                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4554         } else {
4555                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4556                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4557         }
4558
4559         assert_eq!(node_txn[1].input.len(), 1);
4560         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4561
4562         check_spends!(node_txn[2], chan_1.3);
4563
4564         mine_transaction(&nodes[0], &node_txn[1]);
4565         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4566
4567         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4568         // didn't try to generate any new transactions.
4569
4570         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4571         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4572         assert_eq!(spend_txn.len(), 3);
4573         assert_eq!(spend_txn[0].input.len(), 1);
4574         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4575         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4576         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4577         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4578 }
4579
4580 #[test]
4581 fn test_onchain_to_onchain_claim() {
4582         // Test that in case of channel closure, we detect the state of output and claim HTLC
4583         // on downstream peer's remote commitment tx.
4584         // First, have C claim an HTLC against its own latest commitment transaction.
4585         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4586         // channel.
4587         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4588         // gets broadcast.
4589
4590         let chanmon_cfgs = create_chanmon_cfgs(3);
4591         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4592         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4593         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4594
4595         // Create some initial channels
4596         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4597         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4598
4599         // Ensure all nodes are at the same height
4600         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4601         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4602         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4603         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4604
4605         // Rebalance the network a bit by relaying one payment through all the channels ...
4606         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4607         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4608
4609         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4610         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4611         check_spends!(commitment_tx[0], chan_2.3);
4612         nodes[2].node.claim_funds(payment_preimage);
4613         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4614         check_added_monitors!(nodes[2], 1);
4615         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4616         assert!(updates.update_add_htlcs.is_empty());
4617         assert!(updates.update_fail_htlcs.is_empty());
4618         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4619         assert!(updates.update_fail_malformed_htlcs.is_empty());
4620
4621         mine_transaction(&nodes[2], &commitment_tx[0]);
4622         check_closed_broadcast!(nodes[2], true);
4623         check_added_monitors!(nodes[2], 1);
4624         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4625
4626         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
4627         assert_eq!(c_txn.len(), 3);
4628         assert_eq!(c_txn[0], c_txn[2]);
4629         assert_eq!(commitment_tx[0], c_txn[1]);
4630         check_spends!(c_txn[1], chan_2.3);
4631         check_spends!(c_txn[2], c_txn[1]);
4632         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
4633         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4634         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4635         assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4636
4637         // 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
4638         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
4639         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
4640         check_added_monitors!(nodes[1], 1);
4641         let events = nodes[1].node.get_and_clear_pending_events();
4642         assert_eq!(events.len(), 2);
4643         match events[0] {
4644                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4645                 _ => panic!("Unexpected event"),
4646         }
4647         match events[1] {
4648                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
4649                         assert_eq!(fee_earned_msat, Some(1000));
4650                         assert_eq!(prev_channel_id, Some(chan_1.2));
4651                         assert_eq!(claim_from_onchain_tx, true);
4652                         assert_eq!(next_channel_id, Some(chan_2.2));
4653                 },
4654                 _ => panic!("Unexpected event"),
4655         }
4656         {
4657                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4658                 // ChannelMonitor: claim tx
4659                 assert_eq!(b_txn.len(), 1);
4660                 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
4661                 b_txn.clear();
4662         }
4663         check_added_monitors!(nodes[1], 1);
4664         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4665         assert_eq!(msg_events.len(), 3);
4666         match msg_events[0] {
4667                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4668                 _ => panic!("Unexpected event"),
4669         }
4670         match msg_events[1] {
4671                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4672                 _ => panic!("Unexpected event"),
4673         }
4674         match msg_events[2] {
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         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4685         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4686         mine_transaction(&nodes[1], &commitment_tx[0]);
4687         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4688         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4689         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
4690         assert_eq!(b_txn.len(), 3);
4691         check_spends!(b_txn[1], chan_1.3);
4692         check_spends!(b_txn[2], b_txn[1]);
4693         check_spends!(b_txn[0], commitment_tx[0]);
4694         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4695         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4696         assert_eq!(b_txn[0].lock_time.0, 0); // Success tx
4697
4698         check_closed_broadcast!(nodes[1], true);
4699         check_added_monitors!(nodes[1], 1);
4700 }
4701
4702 #[test]
4703 fn test_duplicate_payment_hash_one_failure_one_success() {
4704         // Topology : A --> B --> C --> D
4705         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4706         // Note that because C will refuse to generate two payment secrets for the same payment hash,
4707         // we forward one of the payments onwards to D.
4708         let chanmon_cfgs = create_chanmon_cfgs(4);
4709         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4710         // When this test was written, the default base fee floated based on the HTLC count.
4711         // It is now fixed, so we simply set the fee to the expected value here.
4712         let mut config = test_default_channel_config();
4713         config.channel_config.forwarding_fee_base_msat = 196;
4714         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4715                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4716         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4717
4718         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4719         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4720         create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4721
4722         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4723         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4724         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4725         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4726         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4727
4728         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4729
4730         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
4731         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4732         // script push size limit so that the below script length checks match
4733         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4734         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
4735                 .with_features(channelmanager::provided_invoice_features());
4736         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 900000, TEST_FINAL_CLTV - 40);
4737         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
4738
4739         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4740         assert_eq!(commitment_txn[0].input.len(), 1);
4741         check_spends!(commitment_txn[0], chan_2.3);
4742
4743         mine_transaction(&nodes[1], &commitment_txn[0]);
4744         check_closed_broadcast!(nodes[1], true);
4745         check_added_monitors!(nodes[1], 1);
4746         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4747         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
4748
4749         let htlc_timeout_tx;
4750         { // Extract one of the two HTLC-Timeout transaction
4751                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4752                 // ChannelMonitor: timeout tx * 2-or-3, ChannelManager: local commitment tx
4753                 assert!(node_txn.len() == 4 || node_txn.len() == 3);
4754                 check_spends!(node_txn[0], chan_2.3);
4755
4756                 check_spends!(node_txn[1], commitment_txn[0]);
4757                 assert_eq!(node_txn[1].input.len(), 1);
4758
4759                 if node_txn.len() > 3 {
4760                         check_spends!(node_txn[2], commitment_txn[0]);
4761                         assert_eq!(node_txn[2].input.len(), 1);
4762                         assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
4763
4764                         check_spends!(node_txn[3], commitment_txn[0]);
4765                         assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
4766                 } else {
4767                         check_spends!(node_txn[2], commitment_txn[0]);
4768                         assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
4769                 }
4770
4771                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4772                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4773                 if node_txn.len() > 3 {
4774                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4775                 }
4776                 htlc_timeout_tx = node_txn[1].clone();
4777         }
4778
4779         nodes[2].node.claim_funds(our_payment_preimage);
4780         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4781
4782         mine_transaction(&nodes[2], &commitment_txn[0]);
4783         check_added_monitors!(nodes[2], 2);
4784         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4785         let events = nodes[2].node.get_and_clear_pending_msg_events();
4786         match events[0] {
4787                 MessageSendEvent::UpdateHTLCs { .. } => {},
4788                 _ => panic!("Unexpected event"),
4789         }
4790         match events[1] {
4791                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4792                 _ => panic!("Unexepected event"),
4793         }
4794         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4795         assert_eq!(htlc_success_txn.len(), 5); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs), ChannelManager: local commitment tx + HTLC-Success txn (*2 due to 2-HTLC outputs)
4796         check_spends!(htlc_success_txn[0], commitment_txn[0]);
4797         check_spends!(htlc_success_txn[1], commitment_txn[0]);
4798         assert_eq!(htlc_success_txn[0].input.len(), 1);
4799         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4800         assert_eq!(htlc_success_txn[1].input.len(), 1);
4801         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4802         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4803         assert_eq!(htlc_success_txn[2], commitment_txn[0]);
4804         assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
4805         assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
4806         assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4807
4808         mine_transaction(&nodes[1], &htlc_timeout_tx);
4809         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4810         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 }]);
4811         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4812         assert!(htlc_updates.update_add_htlcs.is_empty());
4813         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4814         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4815         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4816         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4817         check_added_monitors!(nodes[1], 1);
4818
4819         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4820         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4821         {
4822                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4823         }
4824         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
4825
4826         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4827         // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
4828         // and nodes[2] fee) is rounded down and then claimed in full.
4829         mine_transaction(&nodes[1], &htlc_success_txn[1]);
4830         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196*2), true, true);
4831         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4832         assert!(updates.update_add_htlcs.is_empty());
4833         assert!(updates.update_fail_htlcs.is_empty());
4834         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4835         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
4836         assert!(updates.update_fail_malformed_htlcs.is_empty());
4837         check_added_monitors!(nodes[1], 1);
4838
4839         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4840         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4841
4842         let events = nodes[0].node.get_and_clear_pending_events();
4843         match events[0] {
4844                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4845                         assert_eq!(*payment_preimage, our_payment_preimage);
4846                         assert_eq!(*payment_hash, duplicate_payment_hash);
4847                 }
4848                 _ => panic!("Unexpected event"),
4849         }
4850 }
4851
4852 #[test]
4853 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4854         let chanmon_cfgs = create_chanmon_cfgs(2);
4855         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4856         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4857         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4858
4859         // Create some initial channels
4860         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4861
4862         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
4863         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4864         assert_eq!(local_txn.len(), 1);
4865         assert_eq!(local_txn[0].input.len(), 1);
4866         check_spends!(local_txn[0], chan_1.3);
4867
4868         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4869         nodes[1].node.claim_funds(payment_preimage);
4870         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
4871         check_added_monitors!(nodes[1], 1);
4872
4873         mine_transaction(&nodes[1], &local_txn[0]);
4874         check_added_monitors!(nodes[1], 1);
4875         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4876         let events = nodes[1].node.get_and_clear_pending_msg_events();
4877         match events[0] {
4878                 MessageSendEvent::UpdateHTLCs { .. } => {},
4879                 _ => panic!("Unexpected event"),
4880         }
4881         match events[1] {
4882                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4883                 _ => panic!("Unexepected event"),
4884         }
4885         let node_tx = {
4886                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4887                 assert_eq!(node_txn.len(), 3);
4888                 assert_eq!(node_txn[0], node_txn[2]);
4889                 assert_eq!(node_txn[1], local_txn[0]);
4890                 assert_eq!(node_txn[0].input.len(), 1);
4891                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4892                 check_spends!(node_txn[0], local_txn[0]);
4893                 node_txn[0].clone()
4894         };
4895
4896         mine_transaction(&nodes[1], &node_tx);
4897         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4898
4899         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4900         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4901         assert_eq!(spend_txn.len(), 1);
4902         assert_eq!(spend_txn[0].input.len(), 1);
4903         check_spends!(spend_txn[0], node_tx);
4904         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4905 }
4906
4907 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4908         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4909         // unrevoked commitment transaction.
4910         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4911         // a remote RAA before they could be failed backwards (and combinations thereof).
4912         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4913         // use the same payment hashes.
4914         // Thus, we use a six-node network:
4915         //
4916         // A \         / E
4917         //    - C - D -
4918         // B /         \ F
4919         // And test where C fails back to A/B when D announces its latest commitment transaction
4920         let chanmon_cfgs = create_chanmon_cfgs(6);
4921         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4922         // When this test was written, the default base fee floated based on the HTLC count.
4923         // It is now fixed, so we simply set the fee to the expected value here.
4924         let mut config = test_default_channel_config();
4925         config.channel_config.forwarding_fee_base_msat = 196;
4926         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
4927                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4928         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4929
4930         let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4931         let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4932         let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4933         let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4934         let chan_3_5  = create_announced_chan_between_nodes(&nodes, 3, 5, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4935
4936         // Rebalance and check output sanity...
4937         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
4938         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
4939         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
4940
4941         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
4942         // 0th HTLC:
4943         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
4944         // 1st HTLC:
4945         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
4946         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4947         // 2nd HTLC:
4948         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).unwrap()); // not added < dust limit + HTLC tx fee
4949         // 3rd HTLC:
4950         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).unwrap()); // not added < dust limit + HTLC tx fee
4951         // 4th HTLC:
4952         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4953         // 5th HTLC:
4954         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4955         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
4956         // 6th HTLC:
4957         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).unwrap());
4958         // 7th HTLC:
4959         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).unwrap());
4960
4961         // 8th HTLC:
4962         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4963         // 9th HTLC:
4964         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4965         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).unwrap()); // not added < dust limit + HTLC tx fee
4966
4967         // 10th HTLC:
4968         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
4969         // 11th HTLC:
4970         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
4971         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).unwrap());
4972
4973         // Double-check that six of the new HTLC were added
4974         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
4975         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
4976         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
4977         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
4978
4979         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
4980         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
4981         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
4982         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
4983         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
4984         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
4985         check_added_monitors!(nodes[4], 0);
4986
4987         let failed_destinations = vec![
4988                 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
4989                 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
4990                 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
4991                 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
4992         ];
4993         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
4994         check_added_monitors!(nodes[4], 1);
4995
4996         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
4997         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
4998         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
4999         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5000         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5001         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5002
5003         // Fail 3rd below-dust and 7th above-dust HTLCs
5004         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5005         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5006         check_added_monitors!(nodes[5], 0);
5007
5008         let failed_destinations_2 = vec![
5009                 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5010                 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5011         ];
5012         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5013         check_added_monitors!(nodes[5], 1);
5014
5015         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5016         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5017         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5018         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5019
5020         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5021
5022         // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5023         let failed_destinations_3 = vec![
5024                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5025                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5026                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5027                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5028                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5029                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5030         ];
5031         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5032         check_added_monitors!(nodes[3], 1);
5033         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5034         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5035         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5036         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5037         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5038         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5039         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5040         if deliver_last_raa {
5041                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5042         } else {
5043                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5044         }
5045
5046         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5047         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5048         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5049         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5050         //
5051         // We now broadcast the latest commitment transaction, which *should* result in failures for
5052         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5053         // the non-broadcast above-dust HTLCs.
5054         //
5055         // Alternatively, we may broadcast the previous commitment transaction, which should only
5056         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5057         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5058
5059         if announce_latest {
5060                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5061         } else {
5062                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5063         }
5064         let events = nodes[2].node.get_and_clear_pending_events();
5065         let close_event = if deliver_last_raa {
5066                 assert_eq!(events.len(), 2 + 6);
5067                 events.last().clone().unwrap()
5068         } else {
5069                 assert_eq!(events.len(), 1);
5070                 events.last().clone().unwrap()
5071         };
5072         match close_event {
5073                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5074                 _ => panic!("Unexpected event"),
5075         }
5076
5077         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5078         check_closed_broadcast!(nodes[2], true);
5079         if deliver_last_raa {
5080                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5081
5082                 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();
5083                 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5084         } else {
5085                 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5086                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5087                 } else {
5088                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5089                 };
5090
5091                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5092         }
5093         check_added_monitors!(nodes[2], 3);
5094
5095         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5096         assert_eq!(cs_msgs.len(), 2);
5097         let mut a_done = false;
5098         for msg in cs_msgs {
5099                 match msg {
5100                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5101                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5102                                 // should be failed-backwards here.
5103                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5104                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5105                                         for htlc in &updates.update_fail_htlcs {
5106                                                 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 });
5107                                         }
5108                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5109                                         assert!(!a_done);
5110                                         a_done = true;
5111                                         &nodes[0]
5112                                 } else {
5113                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5114                                         for htlc in &updates.update_fail_htlcs {
5115                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5116                                         }
5117                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5118                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5119                                         &nodes[1]
5120                                 };
5121                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5122                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5123                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5124                                 if announce_latest {
5125                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5126                                         if *node_id == nodes[0].node.get_our_node_id() {
5127                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5128                                         }
5129                                 }
5130                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5131                         },
5132                         _ => panic!("Unexpected event"),
5133                 }
5134         }
5135
5136         let as_events = nodes[0].node.get_and_clear_pending_events();
5137         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5138         let mut as_failds = HashSet::new();
5139         let mut as_updates = 0;
5140         for event in as_events.iter() {
5141                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref network_update, .. } = event {
5142                         assert!(as_failds.insert(*payment_hash));
5143                         if *payment_hash != payment_hash_2 {
5144                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5145                         } else {
5146                                 assert!(!payment_failed_permanently);
5147                         }
5148                         if network_update.is_some() {
5149                                 as_updates += 1;
5150                         }
5151                 } else { panic!("Unexpected event"); }
5152         }
5153         assert!(as_failds.contains(&payment_hash_1));
5154         assert!(as_failds.contains(&payment_hash_2));
5155         if announce_latest {
5156                 assert!(as_failds.contains(&payment_hash_3));
5157                 assert!(as_failds.contains(&payment_hash_5));
5158         }
5159         assert!(as_failds.contains(&payment_hash_6));
5160
5161         let bs_events = nodes[1].node.get_and_clear_pending_events();
5162         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5163         let mut bs_failds = HashSet::new();
5164         let mut bs_updates = 0;
5165         for event in bs_events.iter() {
5166                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref network_update, .. } = event {
5167                         assert!(bs_failds.insert(*payment_hash));
5168                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5169                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5170                         } else {
5171                                 assert!(!payment_failed_permanently);
5172                         }
5173                         if network_update.is_some() {
5174                                 bs_updates += 1;
5175                         }
5176                 } else { panic!("Unexpected event"); }
5177         }
5178         assert!(bs_failds.contains(&payment_hash_1));
5179         assert!(bs_failds.contains(&payment_hash_2));
5180         if announce_latest {
5181                 assert!(bs_failds.contains(&payment_hash_4));
5182         }
5183         assert!(bs_failds.contains(&payment_hash_5));
5184
5185         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5186         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5187         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5188         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5189         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5190         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5191 }
5192
5193 #[test]
5194 fn test_fail_backwards_latest_remote_announce_a() {
5195         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5196 }
5197
5198 #[test]
5199 fn test_fail_backwards_latest_remote_announce_b() {
5200         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5201 }
5202
5203 #[test]
5204 fn test_fail_backwards_previous_remote_announce() {
5205         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5206         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5207         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5208 }
5209
5210 #[test]
5211 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5212         let chanmon_cfgs = create_chanmon_cfgs(2);
5213         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5214         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5215         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5216
5217         // Create some initial channels
5218         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5219
5220         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5221         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5222         assert_eq!(local_txn[0].input.len(), 1);
5223         check_spends!(local_txn[0], chan_1.3);
5224
5225         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5226         mine_transaction(&nodes[0], &local_txn[0]);
5227         check_closed_broadcast!(nodes[0], true);
5228         check_added_monitors!(nodes[0], 1);
5229         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5230         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5231
5232         let htlc_timeout = {
5233                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5234                 assert_eq!(node_txn.len(), 2);
5235                 check_spends!(node_txn[0], chan_1.3);
5236                 assert_eq!(node_txn[1].input.len(), 1);
5237                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5238                 check_spends!(node_txn[1], local_txn[0]);
5239                 node_txn[1].clone()
5240         };
5241
5242         mine_transaction(&nodes[0], &htlc_timeout);
5243         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5244         expect_payment_failed!(nodes[0], our_payment_hash, false);
5245
5246         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5247         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5248         assert_eq!(spend_txn.len(), 3);
5249         check_spends!(spend_txn[0], local_txn[0]);
5250         assert_eq!(spend_txn[1].input.len(), 1);
5251         check_spends!(spend_txn[1], htlc_timeout);
5252         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5253         assert_eq!(spend_txn[2].input.len(), 2);
5254         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5255         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5256                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5257 }
5258
5259 #[test]
5260 fn test_key_derivation_params() {
5261         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5262         // manager rotation to test that `channel_keys_id` returned in
5263         // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5264         // then derive a `delayed_payment_key`.
5265
5266         let chanmon_cfgs = create_chanmon_cfgs(3);
5267
5268         // We manually create the node configuration to backup the seed.
5269         let seed = [42; 32];
5270         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5271         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);
5272         let network_graph = NetworkGraph::new(chanmon_cfgs[0].chain_source.genesis_hash, &chanmon_cfgs[0].logger);
5273         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, chain_monitor, keys_manager: &keys_manager, network_graph, node_seed: seed, features: channelmanager::provided_init_features() };
5274         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5275         node_cfgs.remove(0);
5276         node_cfgs.insert(0, node);
5277
5278         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5279         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5280
5281         // Create some initial channels
5282         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5283         // for node 0
5284         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5285         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5286         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5287
5288         // Ensure all nodes are at the same height
5289         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5290         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5291         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5292         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5293
5294         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5295         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5296         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5297         assert_eq!(local_txn_1[0].input.len(), 1);
5298         check_spends!(local_txn_1[0], chan_1.3);
5299
5300         // We check funding pubkey are unique
5301         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]));
5302         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]));
5303         if from_0_funding_key_0 == from_1_funding_key_0
5304             || from_0_funding_key_0 == from_1_funding_key_1
5305             || from_0_funding_key_1 == from_1_funding_key_0
5306             || from_0_funding_key_1 == from_1_funding_key_1 {
5307                 panic!("Funding pubkeys aren't unique");
5308         }
5309
5310         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5311         mine_transaction(&nodes[0], &local_txn_1[0]);
5312         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5313         check_closed_broadcast!(nodes[0], true);
5314         check_added_monitors!(nodes[0], 1);
5315         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5316
5317         let htlc_timeout = {
5318                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5319                 assert_eq!(node_txn[1].input.len(), 1);
5320                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5321                 check_spends!(node_txn[1], local_txn_1[0]);
5322                 node_txn[1].clone()
5323         };
5324
5325         mine_transaction(&nodes[0], &htlc_timeout);
5326         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5327         expect_payment_failed!(nodes[0], our_payment_hash, false);
5328
5329         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5330         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5331         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5332         assert_eq!(spend_txn.len(), 3);
5333         check_spends!(spend_txn[0], local_txn_1[0]);
5334         assert_eq!(spend_txn[1].input.len(), 1);
5335         check_spends!(spend_txn[1], htlc_timeout);
5336         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5337         assert_eq!(spend_txn[2].input.len(), 2);
5338         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5339         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5340                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5341 }
5342
5343 #[test]
5344 fn test_static_output_closing_tx() {
5345         let chanmon_cfgs = create_chanmon_cfgs(2);
5346         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5347         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5348         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5349
5350         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5351
5352         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5353         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5354
5355         mine_transaction(&nodes[0], &closing_tx);
5356         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5357         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5358
5359         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5360         assert_eq!(spend_txn.len(), 1);
5361         check_spends!(spend_txn[0], closing_tx);
5362
5363         mine_transaction(&nodes[1], &closing_tx);
5364         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5365         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5366
5367         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5368         assert_eq!(spend_txn.len(), 1);
5369         check_spends!(spend_txn[0], closing_tx);
5370 }
5371
5372 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5373         let chanmon_cfgs = create_chanmon_cfgs(2);
5374         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5375         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5376         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5377         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5378
5379         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5380
5381         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5382         // present in B's local commitment transaction, but none of A's commitment transactions.
5383         nodes[1].node.claim_funds(payment_preimage);
5384         check_added_monitors!(nodes[1], 1);
5385         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5386
5387         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5388         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5389         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5390
5391         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5392         check_added_monitors!(nodes[0], 1);
5393         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5394         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5395         check_added_monitors!(nodes[1], 1);
5396
5397         let starting_block = nodes[1].best_block_info();
5398         let mut block = Block {
5399                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5400                 txdata: vec![],
5401         };
5402         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5403                 connect_block(&nodes[1], &block);
5404                 block.header.prev_blockhash = block.block_hash();
5405         }
5406         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5407         check_closed_broadcast!(nodes[1], true);
5408         check_added_monitors!(nodes[1], 1);
5409         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5410 }
5411
5412 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5413         let chanmon_cfgs = create_chanmon_cfgs(2);
5414         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5415         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5416         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5417         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5418
5419         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5420         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
5421         check_added_monitors!(nodes[0], 1);
5422
5423         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5424
5425         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5426         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5427         // to "time out" the HTLC.
5428
5429         let starting_block = nodes[1].best_block_info();
5430         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5431
5432         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5433                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5434                 header.prev_blockhash = header.block_hash();
5435         }
5436         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5437         check_closed_broadcast!(nodes[0], true);
5438         check_added_monitors!(nodes[0], 1);
5439         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5440 }
5441
5442 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5443         let chanmon_cfgs = create_chanmon_cfgs(3);
5444         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5445         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5446         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5447         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5448
5449         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5450         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5451         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5452         // actually revoked.
5453         let htlc_value = if use_dust { 50000 } else { 3000000 };
5454         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5455         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5456         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5457         check_added_monitors!(nodes[1], 1);
5458
5459         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5460         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5461         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5462         check_added_monitors!(nodes[0], 1);
5463         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5464         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5465         check_added_monitors!(nodes[1], 1);
5466         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5467         check_added_monitors!(nodes[1], 1);
5468         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5469
5470         if check_revoke_no_close {
5471                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5472                 check_added_monitors!(nodes[0], 1);
5473         }
5474
5475         let starting_block = nodes[1].best_block_info();
5476         let mut block = Block {
5477                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5478                 txdata: vec![],
5479         };
5480         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5481                 connect_block(&nodes[0], &block);
5482                 block.header.prev_blockhash = block.block_hash();
5483         }
5484         if !check_revoke_no_close {
5485                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5486                 check_closed_broadcast!(nodes[0], true);
5487                 check_added_monitors!(nodes[0], 1);
5488                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5489         } else {
5490                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5491         }
5492 }
5493
5494 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5495 // There are only a few cases to test here:
5496 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5497 //    broadcastable commitment transactions result in channel closure,
5498 //  * its included in an unrevoked-but-previous remote commitment transaction,
5499 //  * its included in the latest remote or local commitment transactions.
5500 // We test each of the three possible commitment transactions individually and use both dust and
5501 // non-dust HTLCs.
5502 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5503 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5504 // tested for at least one of the cases in other tests.
5505 #[test]
5506 fn htlc_claim_single_commitment_only_a() {
5507         do_htlc_claim_local_commitment_only(true);
5508         do_htlc_claim_local_commitment_only(false);
5509
5510         do_htlc_claim_current_remote_commitment_only(true);
5511         do_htlc_claim_current_remote_commitment_only(false);
5512 }
5513
5514 #[test]
5515 fn htlc_claim_single_commitment_only_b() {
5516         do_htlc_claim_previous_remote_commitment_only(true, false);
5517         do_htlc_claim_previous_remote_commitment_only(false, false);
5518         do_htlc_claim_previous_remote_commitment_only(true, true);
5519         do_htlc_claim_previous_remote_commitment_only(false, true);
5520 }
5521
5522 #[test]
5523 #[should_panic]
5524 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5525         let chanmon_cfgs = create_chanmon_cfgs(2);
5526         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5527         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5528         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5529         // Force duplicate randomness for every get-random call
5530         for node in nodes.iter() {
5531                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5532         }
5533
5534         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5535         let channel_value_satoshis=10000;
5536         let push_msat=10001;
5537         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5538         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5539         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &node0_to_1_send_open_channel);
5540         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5541
5542         // Create a second channel with the same random values. This used to panic due to a colliding
5543         // channel_id, but now panics due to a colliding outbound SCID alias.
5544         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5545 }
5546
5547 #[test]
5548 fn bolt2_open_channel_sending_node_checks_part2() {
5549         let chanmon_cfgs = create_chanmon_cfgs(2);
5550         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5551         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5552         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5553
5554         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5555         let channel_value_satoshis=2^24;
5556         let push_msat=10001;
5557         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5558
5559         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5560         let channel_value_satoshis=10000;
5561         // Test when push_msat is equal to 1000 * funding_satoshis.
5562         let push_msat=1000*channel_value_satoshis+1;
5563         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5564
5565         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5566         let channel_value_satoshis=10000;
5567         let push_msat=10001;
5568         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
5569         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5570         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5571
5572         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5573         // 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
5574         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5575
5576         // 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.
5577         assert!(BREAKDOWN_TIMEOUT>0);
5578         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5579
5580         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5581         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5582         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5583
5584         // 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.
5585         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5586         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5587         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5588         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5589         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5590 }
5591
5592 #[test]
5593 fn bolt2_open_channel_sane_dust_limit() {
5594         let chanmon_cfgs = create_chanmon_cfgs(2);
5595         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5596         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5597         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5598
5599         let channel_value_satoshis=1000000;
5600         let push_msat=10001;
5601         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5602         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5603         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5604         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5605
5606         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &node0_to_1_send_open_channel);
5607         let events = nodes[1].node.get_and_clear_pending_msg_events();
5608         let err_msg = match events[0] {
5609                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5610                         msg.clone()
5611                 },
5612                 _ => panic!("Unexpected event"),
5613         };
5614         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5615 }
5616
5617 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5618 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5619 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5620 // is no longer affordable once it's freed.
5621 #[test]
5622 fn test_fail_holding_cell_htlc_upon_free() {
5623         let chanmon_cfgs = create_chanmon_cfgs(2);
5624         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5625         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5626         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5627         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5628
5629         // First nodes[0] generates an update_fee, setting the channel's
5630         // pending_update_fee.
5631         {
5632                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5633                 *feerate_lock += 20;
5634         }
5635         nodes[0].node.timer_tick_occurred();
5636         check_added_monitors!(nodes[0], 1);
5637
5638         let events = nodes[0].node.get_and_clear_pending_msg_events();
5639         assert_eq!(events.len(), 1);
5640         let (update_msg, commitment_signed) = match events[0] {
5641                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5642                         (update_fee.as_ref(), commitment_signed)
5643                 },
5644                 _ => panic!("Unexpected event"),
5645         };
5646
5647         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5648
5649         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5650         let channel_reserve = chan_stat.channel_reserve_msat;
5651         let feerate = get_feerate!(nodes[0], chan.2);
5652         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
5653
5654         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5655         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5656         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5657
5658         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5659         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5660         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5661         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5662
5663         // Flush the pending fee update.
5664         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5665         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5666         check_added_monitors!(nodes[1], 1);
5667         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5668         check_added_monitors!(nodes[0], 1);
5669
5670         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5671         // HTLC, but now that the fee has been raised the payment will now fail, causing
5672         // us to surface its failure to the user.
5673         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5674         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5675         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);
5676         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 {}",
5677                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5678         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5679
5680         // Check that the payment failed to be sent out.
5681         let events = nodes[0].node.get_and_clear_pending_events();
5682         assert_eq!(events.len(), 1);
5683         match &events[0] {
5684                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update, ref all_paths_failed, ref short_channel_id, .. } => {
5685                         assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5686                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5687                         assert_eq!(*payment_failed_permanently, false);
5688                         assert_eq!(*all_paths_failed, true);
5689                         assert_eq!(*network_update, None);
5690                         assert_eq!(*short_channel_id, Some(route.paths[0][0].short_channel_id));
5691                 },
5692                 _ => panic!("Unexpected event"),
5693         }
5694 }
5695
5696 // Test that if multiple HTLCs are released from the holding cell and one is
5697 // valid but the other is no longer valid upon release, the valid HTLC can be
5698 // successfully completed while the other one fails as expected.
5699 #[test]
5700 fn test_free_and_fail_holding_cell_htlcs() {
5701         let chanmon_cfgs = create_chanmon_cfgs(2);
5702         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5703         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5704         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5705         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5706
5707         // First nodes[0] generates an update_fee, setting the channel's
5708         // pending_update_fee.
5709         {
5710                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5711                 *feerate_lock += 200;
5712         }
5713         nodes[0].node.timer_tick_occurred();
5714         check_added_monitors!(nodes[0], 1);
5715
5716         let events = nodes[0].node.get_and_clear_pending_msg_events();
5717         assert_eq!(events.len(), 1);
5718         let (update_msg, commitment_signed) = match events[0] {
5719                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5720                         (update_fee.as_ref(), commitment_signed)
5721                 },
5722                 _ => panic!("Unexpected event"),
5723         };
5724
5725         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5726
5727         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5728         let channel_reserve = chan_stat.channel_reserve_msat;
5729         let feerate = get_feerate!(nodes[0], chan.2);
5730         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
5731
5732         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5733         let amt_1 = 20000;
5734         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
5735         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5736         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5737
5738         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5739         nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5740         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5741         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5742         let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5743         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2), payment_id_2).unwrap();
5744         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5745         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5746
5747         // Flush the pending fee update.
5748         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5749         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5750         check_added_monitors!(nodes[1], 1);
5751         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5752         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5753         check_added_monitors!(nodes[0], 2);
5754
5755         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5756         // but now that the fee has been raised the second payment will now fail, causing us
5757         // to surface its failure to the user. The first payment should succeed.
5758         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5759         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5760         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);
5761         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 {}",
5762                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5763         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5764
5765         // Check that the second payment failed to be sent out.
5766         let events = nodes[0].node.get_and_clear_pending_events();
5767         assert_eq!(events.len(), 1);
5768         match &events[0] {
5769                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update, ref all_paths_failed, ref short_channel_id, .. } => {
5770                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5771                         assert_eq!(payment_hash_2.clone(), *payment_hash);
5772                         assert_eq!(*payment_failed_permanently, false);
5773                         assert_eq!(*all_paths_failed, true);
5774                         assert_eq!(*network_update, None);
5775                         assert_eq!(*short_channel_id, Some(route_2.paths[0][0].short_channel_id));
5776                 },
5777                 _ => panic!("Unexpected event"),
5778         }
5779
5780         // Complete the first payment and the RAA from the fee update.
5781         let (payment_event, send_raa_event) = {
5782                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5783                 assert_eq!(msgs.len(), 2);
5784                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5785         };
5786         let raa = match send_raa_event {
5787                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5788                 _ => panic!("Unexpected event"),
5789         };
5790         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5791         check_added_monitors!(nodes[1], 1);
5792         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5793         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5794         let events = nodes[1].node.get_and_clear_pending_events();
5795         assert_eq!(events.len(), 1);
5796         match events[0] {
5797                 Event::PendingHTLCsForwardable { .. } => {},
5798                 _ => panic!("Unexpected event"),
5799         }
5800         nodes[1].node.process_pending_htlc_forwards();
5801         let events = nodes[1].node.get_and_clear_pending_events();
5802         assert_eq!(events.len(), 1);
5803         match events[0] {
5804                 Event::PaymentClaimable { .. } => {},
5805                 _ => panic!("Unexpected event"),
5806         }
5807         nodes[1].node.claim_funds(payment_preimage_1);
5808         check_added_monitors!(nodes[1], 1);
5809         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5810
5811         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5812         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5813         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5814         expect_payment_sent!(nodes[0], payment_preimage_1);
5815 }
5816
5817 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
5818 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
5819 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
5820 // once it's freed.
5821 #[test]
5822 fn test_fail_holding_cell_htlc_upon_free_multihop() {
5823         let chanmon_cfgs = create_chanmon_cfgs(3);
5824         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5825         // When this test was written, the default base fee floated based on the HTLC count.
5826         // It is now fixed, so we simply set the fee to the expected value here.
5827         let mut config = test_default_channel_config();
5828         config.channel_config.forwarding_fee_base_msat = 196;
5829         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5830         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5831         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5832         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5833
5834         // First nodes[1] generates an update_fee, setting the channel's
5835         // pending_update_fee.
5836         {
5837                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
5838                 *feerate_lock += 20;
5839         }
5840         nodes[1].node.timer_tick_occurred();
5841         check_added_monitors!(nodes[1], 1);
5842
5843         let events = nodes[1].node.get_and_clear_pending_msg_events();
5844         assert_eq!(events.len(), 1);
5845         let (update_msg, commitment_signed) = match events[0] {
5846                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5847                         (update_fee.as_ref(), commitment_signed)
5848                 },
5849                 _ => panic!("Unexpected event"),
5850         };
5851
5852         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
5853
5854         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
5855         let channel_reserve = chan_stat.channel_reserve_msat;
5856         let feerate = get_feerate!(nodes[0], chan_0_1.2);
5857         let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
5858
5859         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5860         let feemsat = 239;
5861         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
5862         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
5863         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
5864         let payment_event = {
5865                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5866                 check_added_monitors!(nodes[0], 1);
5867
5868                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5869                 assert_eq!(events.len(), 1);
5870
5871                 SendEvent::from_event(events.remove(0))
5872         };
5873         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5874         check_added_monitors!(nodes[1], 0);
5875         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5876         expect_pending_htlcs_forwardable!(nodes[1]);
5877
5878         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
5879         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5880
5881         // Flush the pending fee update.
5882         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
5883         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5884         check_added_monitors!(nodes[2], 1);
5885         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
5886         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
5887         check_added_monitors!(nodes[1], 2);
5888
5889         // A final RAA message is generated to finalize the fee update.
5890         let events = nodes[1].node.get_and_clear_pending_msg_events();
5891         assert_eq!(events.len(), 1);
5892
5893         let raa_msg = match &events[0] {
5894                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
5895                         msg.clone()
5896                 },
5897                 _ => panic!("Unexpected event"),
5898         };
5899
5900         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
5901         check_added_monitors!(nodes[2], 1);
5902         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
5903
5904         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
5905         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
5906         assert_eq!(process_htlc_forwards_event.len(), 2);
5907         match &process_htlc_forwards_event[0] {
5908                 &Event::PendingHTLCsForwardable { .. } => {},
5909                 _ => panic!("Unexpected event"),
5910         }
5911
5912         // In response, we call ChannelManager's process_pending_htlc_forwards
5913         nodes[1].node.process_pending_htlc_forwards();
5914         check_added_monitors!(nodes[1], 1);
5915
5916         // This causes the HTLC to be failed backwards.
5917         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
5918         assert_eq!(fail_event.len(), 1);
5919         let (fail_msg, commitment_signed) = match &fail_event[0] {
5920                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
5921                         assert_eq!(updates.update_add_htlcs.len(), 0);
5922                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
5923                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
5924                         assert_eq!(updates.update_fail_htlcs.len(), 1);
5925                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
5926                 },
5927                 _ => panic!("Unexpected event"),
5928         };
5929
5930         // Pass the failure messages back to nodes[0].
5931         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5932         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5933
5934         // Complete the HTLC failure+removal process.
5935         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5936         check_added_monitors!(nodes[0], 1);
5937         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5938         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
5939         check_added_monitors!(nodes[1], 2);
5940         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
5941         assert_eq!(final_raa_event.len(), 1);
5942         let raa = match &final_raa_event[0] {
5943                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
5944                 _ => panic!("Unexpected event"),
5945         };
5946         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
5947         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
5948         check_added_monitors!(nodes[0], 1);
5949 }
5950
5951 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
5952 // 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.
5953 //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.
5954
5955 #[test]
5956 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
5957         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
5958         let chanmon_cfgs = create_chanmon_cfgs(2);
5959         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5960         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5961         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5962         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5963
5964         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
5965         route.paths[0][0].fee_msat = 100;
5966
5967         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 },
5968                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
5969         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5970         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
5971 }
5972
5973 #[test]
5974 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
5975         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
5976         let chanmon_cfgs = create_chanmon_cfgs(2);
5977         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5978         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5979         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5980         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5981
5982         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
5983         route.paths[0][0].fee_msat = 0;
5984         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 },
5985                 assert_eq!(err, "Cannot send 0-msat HTLC"));
5986
5987         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5988         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
5989 }
5990
5991 #[test]
5992 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
5993         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
5994         let chanmon_cfgs = create_chanmon_cfgs(2);
5995         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5996         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5997         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5998         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5999
6000         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6001         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6002         check_added_monitors!(nodes[0], 1);
6003         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6004         updates.update_add_htlcs[0].amount_msat = 0;
6005
6006         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6007         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6008         check_closed_broadcast!(nodes[1], true).unwrap();
6009         check_added_monitors!(nodes[1], 1);
6010         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6011 }
6012
6013 #[test]
6014 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6015         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6016         //It is enforced when constructing a route.
6017         let chanmon_cfgs = create_chanmon_cfgs(2);
6018         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6019         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6020         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6021         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6022
6023         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
6024                 .with_features(channelmanager::provided_invoice_features());
6025         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6026         route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6027         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 },
6028                 assert_eq!(err, &"Channel CLTV overflowed?"));
6029 }
6030
6031 #[test]
6032 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6033         //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.
6034         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6035         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6036         let chanmon_cfgs = create_chanmon_cfgs(2);
6037         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6038         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6039         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6040         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6041         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6042
6043         for i in 0..max_accepted_htlcs {
6044                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6045                 let payment_event = {
6046                         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6047                         check_added_monitors!(nodes[0], 1);
6048
6049                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6050                         assert_eq!(events.len(), 1);
6051                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6052                                 assert_eq!(htlcs[0].htlc_id, i);
6053                         } else {
6054                                 assert!(false);
6055                         }
6056                         SendEvent::from_event(events.remove(0))
6057                 };
6058                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6059                 check_added_monitors!(nodes[1], 0);
6060                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6061
6062                 expect_pending_htlcs_forwardable!(nodes[1]);
6063                 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6064         }
6065         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6066         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 },
6067                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6068
6069         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6070         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6071 }
6072
6073 #[test]
6074 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6075         //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.
6076         let chanmon_cfgs = create_chanmon_cfgs(2);
6077         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6078         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6079         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6080         let channel_value = 100000;
6081         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6082         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6083
6084         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6085
6086         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6087         // Manually create a route over our max in flight (which our router normally automatically
6088         // limits us to.
6089         route.paths[0][0].fee_msat =  max_in_flight + 1;
6090         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 },
6091                 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)));
6092
6093         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6094         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);
6095
6096         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6097 }
6098
6099 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6100 #[test]
6101 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6102         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6103         let chanmon_cfgs = create_chanmon_cfgs(2);
6104         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6105         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6106         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6107         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6108         let htlc_minimum_msat: u64;
6109         {
6110                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6111                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6112                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6113         }
6114
6115         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6116         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6117         check_added_monitors!(nodes[0], 1);
6118         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6119         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6120         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6121         assert!(nodes[1].node.list_channels().is_empty());
6122         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6123         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()));
6124         check_added_monitors!(nodes[1], 1);
6125         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6126 }
6127
6128 #[test]
6129 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6130         //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
6131         let chanmon_cfgs = create_chanmon_cfgs(2);
6132         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6133         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6134         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6135         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6136
6137         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6138         let channel_reserve = chan_stat.channel_reserve_msat;
6139         let feerate = get_feerate!(nodes[0], chan.2);
6140         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6141         // The 2* and +1 are for the fee spike reserve.
6142         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6143
6144         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6145         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6146         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6147         check_added_monitors!(nodes[0], 1);
6148         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6149
6150         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6151         // at this time channel-initiatee receivers are not required to enforce that senders
6152         // respect the fee_spike_reserve.
6153         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6154         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6155
6156         assert!(nodes[1].node.list_channels().is_empty());
6157         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6158         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6159         check_added_monitors!(nodes[1], 1);
6160         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6161 }
6162
6163 #[test]
6164 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6165         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6166         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6167         let chanmon_cfgs = create_chanmon_cfgs(2);
6168         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6169         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6170         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6171         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6172
6173         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6174         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6175         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6176         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6177         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6178         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6179
6180         let mut msg = msgs::UpdateAddHTLC {
6181                 channel_id: chan.2,
6182                 htlc_id: 0,
6183                 amount_msat: 1000,
6184                 payment_hash: our_payment_hash,
6185                 cltv_expiry: htlc_cltv,
6186                 onion_routing_packet: onion_packet.clone(),
6187         };
6188
6189         for i in 0..super::channel::OUR_MAX_HTLCS {
6190                 msg.htlc_id = i as u64;
6191                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6192         }
6193         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6194         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6195
6196         assert!(nodes[1].node.list_channels().is_empty());
6197         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6198         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6199         check_added_monitors!(nodes[1], 1);
6200         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6201 }
6202
6203 #[test]
6204 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6205         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6206         let chanmon_cfgs = create_chanmon_cfgs(2);
6207         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6208         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6209         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6210         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6211
6212         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6213         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6214         check_added_monitors!(nodes[0], 1);
6215         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6216         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6217         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6218
6219         assert!(nodes[1].node.list_channels().is_empty());
6220         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6221         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6222         check_added_monitors!(nodes[1], 1);
6223         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6224 }
6225
6226 #[test]
6227 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6228         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6229         let chanmon_cfgs = create_chanmon_cfgs(2);
6230         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6231         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6232         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6233
6234         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6235         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6236         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6237         check_added_monitors!(nodes[0], 1);
6238         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6239         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6240         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6241
6242         assert!(nodes[1].node.list_channels().is_empty());
6243         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6244         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6245         check_added_monitors!(nodes[1], 1);
6246         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6247 }
6248
6249 #[test]
6250 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6251         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6252         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6253         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6254         let chanmon_cfgs = create_chanmon_cfgs(2);
6255         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6256         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6257         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6258
6259         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6260         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6261         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6262         check_added_monitors!(nodes[0], 1);
6263         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6264         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6265
6266         //Disconnect and Reconnect
6267         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6268         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6269         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
6270         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6271         assert_eq!(reestablish_1.len(), 1);
6272         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
6273         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6274         assert_eq!(reestablish_2.len(), 1);
6275         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6276         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6277         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6278         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6279
6280         //Resend HTLC
6281         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6282         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6283         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6284         check_added_monitors!(nodes[1], 1);
6285         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6286
6287         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6288
6289         assert!(nodes[1].node.list_channels().is_empty());
6290         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6291         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6292         check_added_monitors!(nodes[1], 1);
6293         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6294 }
6295
6296 #[test]
6297 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6298         //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.
6299
6300         let chanmon_cfgs = create_chanmon_cfgs(2);
6301         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6302         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6303         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6304         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6305         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6306         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6307
6308         check_added_monitors!(nodes[0], 1);
6309         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6310         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6311
6312         let update_msg = msgs::UpdateFulfillHTLC{
6313                 channel_id: chan.2,
6314                 htlc_id: 0,
6315                 payment_preimage: our_payment_preimage,
6316         };
6317
6318         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6319
6320         assert!(nodes[0].node.list_channels().is_empty());
6321         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6322         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()));
6323         check_added_monitors!(nodes[0], 1);
6324         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6325 }
6326
6327 #[test]
6328 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6329         //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.
6330
6331         let chanmon_cfgs = create_chanmon_cfgs(2);
6332         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6333         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6334         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6335         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6336
6337         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6338         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6339         check_added_monitors!(nodes[0], 1);
6340         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6341         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6342
6343         let update_msg = msgs::UpdateFailHTLC{
6344                 channel_id: chan.2,
6345                 htlc_id: 0,
6346                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6347         };
6348
6349         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6350
6351         assert!(nodes[0].node.list_channels().is_empty());
6352         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6353         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()));
6354         check_added_monitors!(nodes[0], 1);
6355         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6356 }
6357
6358 #[test]
6359 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6360         //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.
6361
6362         let chanmon_cfgs = create_chanmon_cfgs(2);
6363         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6364         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6365         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6366         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6367
6368         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6369         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6370         check_added_monitors!(nodes[0], 1);
6371         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6372         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6373         let update_msg = msgs::UpdateFailMalformedHTLC{
6374                 channel_id: chan.2,
6375                 htlc_id: 0,
6376                 sha256_of_onion: [1; 32],
6377                 failure_code: 0x8000,
6378         };
6379
6380         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6381
6382         assert!(nodes[0].node.list_channels().is_empty());
6383         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6384         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()));
6385         check_added_monitors!(nodes[0], 1);
6386         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6387 }
6388
6389 #[test]
6390 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6391         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6392
6393         let chanmon_cfgs = create_chanmon_cfgs(2);
6394         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6395         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6396         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6397         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6398
6399         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6400
6401         nodes[1].node.claim_funds(our_payment_preimage);
6402         check_added_monitors!(nodes[1], 1);
6403         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6404
6405         let events = nodes[1].node.get_and_clear_pending_msg_events();
6406         assert_eq!(events.len(), 1);
6407         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6408                 match events[0] {
6409                         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, .. } } => {
6410                                 assert!(update_add_htlcs.is_empty());
6411                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6412                                 assert!(update_fail_htlcs.is_empty());
6413                                 assert!(update_fail_malformed_htlcs.is_empty());
6414                                 assert!(update_fee.is_none());
6415                                 update_fulfill_htlcs[0].clone()
6416                         },
6417                         _ => panic!("Unexpected event"),
6418                 }
6419         };
6420
6421         update_fulfill_msg.htlc_id = 1;
6422
6423         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6424
6425         assert!(nodes[0].node.list_channels().is_empty());
6426         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6427         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6428         check_added_monitors!(nodes[0], 1);
6429         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6430 }
6431
6432 #[test]
6433 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6434         //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.
6435
6436         let chanmon_cfgs = create_chanmon_cfgs(2);
6437         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6438         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6439         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6440         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6441
6442         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6443
6444         nodes[1].node.claim_funds(our_payment_preimage);
6445         check_added_monitors!(nodes[1], 1);
6446         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6447
6448         let events = nodes[1].node.get_and_clear_pending_msg_events();
6449         assert_eq!(events.len(), 1);
6450         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6451                 match events[0] {
6452                         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, .. } } => {
6453                                 assert!(update_add_htlcs.is_empty());
6454                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6455                                 assert!(update_fail_htlcs.is_empty());
6456                                 assert!(update_fail_malformed_htlcs.is_empty());
6457                                 assert!(update_fee.is_none());
6458                                 update_fulfill_htlcs[0].clone()
6459                         },
6460                         _ => panic!("Unexpected event"),
6461                 }
6462         };
6463
6464         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6465
6466         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6467
6468         assert!(nodes[0].node.list_channels().is_empty());
6469         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6470         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6471         check_added_monitors!(nodes[0], 1);
6472         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6473 }
6474
6475 #[test]
6476 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6477         //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.
6478
6479         let chanmon_cfgs = create_chanmon_cfgs(2);
6480         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6481         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6482         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6483         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6484
6485         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6486         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6487         check_added_monitors!(nodes[0], 1);
6488
6489         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6490         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6491
6492         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6493         check_added_monitors!(nodes[1], 0);
6494         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6495
6496         let events = nodes[1].node.get_and_clear_pending_msg_events();
6497
6498         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6499                 match events[0] {
6500                         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, .. } } => {
6501                                 assert!(update_add_htlcs.is_empty());
6502                                 assert!(update_fulfill_htlcs.is_empty());
6503                                 assert!(update_fail_htlcs.is_empty());
6504                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6505                                 assert!(update_fee.is_none());
6506                                 update_fail_malformed_htlcs[0].clone()
6507                         },
6508                         _ => panic!("Unexpected event"),
6509                 }
6510         };
6511         update_msg.failure_code &= !0x8000;
6512         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6513
6514         assert!(nodes[0].node.list_channels().is_empty());
6515         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6516         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6517         check_added_monitors!(nodes[0], 1);
6518         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6519 }
6520
6521 #[test]
6522 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6523         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6524         //    * 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.
6525
6526         let chanmon_cfgs = create_chanmon_cfgs(3);
6527         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6528         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6529         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6530         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6531         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6532
6533         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6534
6535         //First hop
6536         let mut payment_event = {
6537                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6538                 check_added_monitors!(nodes[0], 1);
6539                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6540                 assert_eq!(events.len(), 1);
6541                 SendEvent::from_event(events.remove(0))
6542         };
6543         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6544         check_added_monitors!(nodes[1], 0);
6545         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6546         expect_pending_htlcs_forwardable!(nodes[1]);
6547         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6548         assert_eq!(events_2.len(), 1);
6549         check_added_monitors!(nodes[1], 1);
6550         payment_event = SendEvent::from_event(events_2.remove(0));
6551         assert_eq!(payment_event.msgs.len(), 1);
6552
6553         //Second Hop
6554         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6555         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6556         check_added_monitors!(nodes[2], 0);
6557         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6558
6559         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6560         assert_eq!(events_3.len(), 1);
6561         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6562                 match events_3[0] {
6563                         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 } } => {
6564                                 assert!(update_add_htlcs.is_empty());
6565                                 assert!(update_fulfill_htlcs.is_empty());
6566                                 assert!(update_fail_htlcs.is_empty());
6567                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6568                                 assert!(update_fee.is_none());
6569                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6570                         },
6571                         _ => panic!("Unexpected event"),
6572                 }
6573         };
6574
6575         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6576
6577         check_added_monitors!(nodes[1], 0);
6578         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6579         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 }]);
6580         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6581         assert_eq!(events_4.len(), 1);
6582
6583         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6584         match events_4[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, .. } } => {
6586                         assert!(update_add_htlcs.is_empty());
6587                         assert!(update_fulfill_htlcs.is_empty());
6588                         assert_eq!(update_fail_htlcs.len(), 1);
6589                         assert!(update_fail_malformed_htlcs.is_empty());
6590                         assert!(update_fee.is_none());
6591                 },
6592                 _ => panic!("Unexpected event"),
6593         };
6594
6595         check_added_monitors!(nodes[1], 1);
6596 }
6597
6598 #[test]
6599 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6600         let chanmon_cfgs = create_chanmon_cfgs(3);
6601         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6602         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6603         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6604         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6605         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6606
6607         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6608
6609         // First hop
6610         let mut payment_event = {
6611                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6612                 check_added_monitors!(nodes[0], 1);
6613                 SendEvent::from_node(&nodes[0])
6614         };
6615
6616         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6617         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6618         expect_pending_htlcs_forwardable!(nodes[1]);
6619         check_added_monitors!(nodes[1], 1);
6620         payment_event = SendEvent::from_node(&nodes[1]);
6621         assert_eq!(payment_event.msgs.len(), 1);
6622
6623         // Second Hop
6624         payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6625         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6626         check_added_monitors!(nodes[2], 0);
6627         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6628
6629         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6630         assert_eq!(events_3.len(), 1);
6631         match events_3[0] {
6632                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6633                         let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6634                         // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6635                         update_msg.failure_code |= 0x2000;
6636
6637                         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6638                         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6639                 },
6640                 _ => panic!("Unexpected event"),
6641         }
6642
6643         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6644                 vec![HTLCDestination::NextHopChannel {
6645                         node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6646         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6647         assert_eq!(events_4.len(), 1);
6648         check_added_monitors!(nodes[1], 1);
6649
6650         match events_4[0] {
6651                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6652                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6653                         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6654                 },
6655                 _ => panic!("Unexpected event"),
6656         }
6657
6658         let events_5 = nodes[0].node.get_and_clear_pending_events();
6659         assert_eq!(events_5.len(), 1);
6660
6661         // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6662         // the node originating the error to its next hop.
6663         match events_5[0] {
6664                 Event::PaymentPathFailed { network_update:
6665                         Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }), error_code, ..
6666                 } => {
6667                         assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6668                         assert!(is_permanent);
6669                         assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6670                 },
6671                 _ => panic!("Unexpected event"),
6672         }
6673
6674         // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6675 }
6676
6677 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6678         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6679         // 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
6680         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6681
6682         let mut chanmon_cfgs = create_chanmon_cfgs(2);
6683         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6684         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6685         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6686         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6687         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6688
6689         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6690
6691         // We route 2 dust-HTLCs between A and B
6692         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6693         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6694         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6695
6696         // Cache one local commitment tx as previous
6697         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6698
6699         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6700         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6701         check_added_monitors!(nodes[1], 0);
6702         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6703         check_added_monitors!(nodes[1], 1);
6704
6705         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6706         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6707         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6708         check_added_monitors!(nodes[0], 1);
6709
6710         // Cache one local commitment tx as lastest
6711         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6712
6713         let events = nodes[0].node.get_and_clear_pending_msg_events();
6714         match events[0] {
6715                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6716                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6717                 },
6718                 _ => panic!("Unexpected event"),
6719         }
6720         match events[1] {
6721                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6722                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6723                 },
6724                 _ => panic!("Unexpected event"),
6725         }
6726
6727         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6728         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6729         if announce_latest {
6730                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6731         } else {
6732                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6733         }
6734
6735         check_closed_broadcast!(nodes[0], true);
6736         check_added_monitors!(nodes[0], 1);
6737         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6738
6739         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6740         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6741         let events = nodes[0].node.get_and_clear_pending_events();
6742         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6743         assert_eq!(events.len(), 2);
6744         let mut first_failed = false;
6745         for event in events {
6746                 match event {
6747                         Event::PaymentPathFailed { payment_hash, .. } => {
6748                                 if payment_hash == payment_hash_1 {
6749                                         assert!(!first_failed);
6750                                         first_failed = true;
6751                                 } else {
6752                                         assert_eq!(payment_hash, payment_hash_2);
6753                                 }
6754                         }
6755                         _ => panic!("Unexpected event"),
6756                 }
6757         }
6758 }
6759
6760 #[test]
6761 fn test_failure_delay_dust_htlc_local_commitment() {
6762         do_test_failure_delay_dust_htlc_local_commitment(true);
6763         do_test_failure_delay_dust_htlc_local_commitment(false);
6764 }
6765
6766 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6767         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6768         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6769         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6770         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6771         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6772         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6773
6774         let chanmon_cfgs = create_chanmon_cfgs(3);
6775         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6776         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6777         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6778         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6779
6780         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6781
6782         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6783         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6784
6785         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6786         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6787
6788         // We revoked bs_commitment_tx
6789         if revoked {
6790                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6791                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6792         }
6793
6794         let mut timeout_tx = Vec::new();
6795         if local {
6796                 // We fail dust-HTLC 1 by broadcast of local commitment tx
6797                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
6798                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6799                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6800                 expect_payment_failed!(nodes[0], dust_hash, false);
6801
6802                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
6803                 check_closed_broadcast!(nodes[0], true);
6804                 check_added_monitors!(nodes[0], 1);
6805                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6806                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
6807                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6808                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6809                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6810                 mine_transaction(&nodes[0], &timeout_tx[0]);
6811                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6812                 expect_payment_failed!(nodes[0], non_dust_hash, false);
6813         } else {
6814                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6815                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
6816                 check_closed_broadcast!(nodes[0], true);
6817                 check_added_monitors!(nodes[0], 1);
6818                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6819                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6820
6821                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
6822                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
6823                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
6824                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
6825                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
6826                 // dust HTLC should have been failed.
6827                 expect_payment_failed!(nodes[0], dust_hash, false);
6828
6829                 if !revoked {
6830                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6831                 } else {
6832                         assert_eq!(timeout_tx[0].lock_time.0, 0);
6833                 }
6834                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
6835                 mine_transaction(&nodes[0], &timeout_tx[0]);
6836                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6837                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6838                 expect_payment_failed!(nodes[0], non_dust_hash, false);
6839         }
6840 }
6841
6842 #[test]
6843 fn test_sweep_outbound_htlc_failure_update() {
6844         do_test_sweep_outbound_htlc_failure_update(false, true);
6845         do_test_sweep_outbound_htlc_failure_update(false, false);
6846         do_test_sweep_outbound_htlc_failure_update(true, false);
6847 }
6848
6849 #[test]
6850 fn test_user_configurable_csv_delay() {
6851         // We test our channel constructors yield errors when we pass them absurd csv delay
6852
6853         let mut low_our_to_self_config = UserConfig::default();
6854         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
6855         let mut high_their_to_self_config = UserConfig::default();
6856         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
6857         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6858         let chanmon_cfgs = create_chanmon_cfgs(2);
6859         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6860         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6861         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6862
6863         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6864         if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6865                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), 1000000, 1000000, 0,
6866                 &low_our_to_self_config, 0, 42)
6867         {
6868                 match error {
6869                         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())); },
6870                         _ => panic!("Unexpected event"),
6871                 }
6872         } else { assert!(false) }
6873
6874         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6875         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6876         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6877         open_channel.to_self_delay = 200;
6878         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6879                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), &open_channel, 0,
6880                 &low_our_to_self_config, 0, &nodes[0].logger, 42)
6881         {
6882                 match error {
6883                         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()));  },
6884                         _ => panic!("Unexpected event"),
6885                 }
6886         } else { assert!(false); }
6887
6888         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6889         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6890         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
6891         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6892         accept_channel.to_self_delay = 200;
6893         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
6894         let reason_msg;
6895         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
6896                 match action {
6897                         &ErrorAction::SendErrorMessage { ref msg } => {
6898                                 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()));
6899                                 reason_msg = msg.data.clone();
6900                         },
6901                         _ => { panic!(); }
6902                 }
6903         } else { panic!(); }
6904         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
6905
6906         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
6907         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6908         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6909         open_channel.to_self_delay = 200;
6910         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6911                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), &open_channel, 0,
6912                 &high_their_to_self_config, 0, &nodes[0].logger, 42)
6913         {
6914                 match error {
6915                         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())); },
6916                         _ => panic!("Unexpected event"),
6917                 }
6918         } else { assert!(false); }
6919 }
6920
6921 #[test]
6922 fn test_check_htlc_underpaying() {
6923         // Send payment through A -> B but A is maliciously
6924         // sending a probe payment (i.e less than expected value0
6925         // to B, B should refuse payment.
6926
6927         let chanmon_cfgs = create_chanmon_cfgs(2);
6928         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6929         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6930         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6931
6932         // Create some initial channels
6933         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6934
6935         let scorer = test_utils::TestScorer::with_penalty(0);
6936         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
6937         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(channelmanager::provided_invoice_features());
6938         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();
6939         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
6940         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
6941         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6942         check_added_monitors!(nodes[0], 1);
6943
6944         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6945         assert_eq!(events.len(), 1);
6946         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
6947         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6948         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6949
6950         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
6951         // and then will wait a second random delay before failing the HTLC back:
6952         expect_pending_htlcs_forwardable!(nodes[1]);
6953         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
6954
6955         // Node 3 is expecting payment of 100_000 but received 10_000,
6956         // it should fail htlc like we didn't know the preimage.
6957         nodes[1].node.process_pending_htlc_forwards();
6958
6959         let events = nodes[1].node.get_and_clear_pending_msg_events();
6960         assert_eq!(events.len(), 1);
6961         let (update_fail_htlc, commitment_signed) = match events[0] {
6962                 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 } } => {
6963                         assert!(update_add_htlcs.is_empty());
6964                         assert!(update_fulfill_htlcs.is_empty());
6965                         assert_eq!(update_fail_htlcs.len(), 1);
6966                         assert!(update_fail_malformed_htlcs.is_empty());
6967                         assert!(update_fee.is_none());
6968                         (update_fail_htlcs[0].clone(), commitment_signed)
6969                 },
6970                 _ => panic!("Unexpected event"),
6971         };
6972         check_added_monitors!(nodes[1], 1);
6973
6974         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
6975         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
6976
6977         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
6978         let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
6979         expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
6980         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
6981 }
6982
6983 #[test]
6984 fn test_announce_disable_channels() {
6985         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
6986         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
6987
6988         let chanmon_cfgs = create_chanmon_cfgs(2);
6989         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6990         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6991         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6992
6993         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6994         create_announced_chan_between_nodes(&nodes, 1, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6995         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6996
6997         // Disconnect peers
6998         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6999         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7000
7001         nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7002         nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7003         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7004         assert_eq!(msg_events.len(), 3);
7005         let mut chans_disabled = HashMap::new();
7006         for e in msg_events {
7007                 match e {
7008                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7009                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7010                                 // Check that each channel gets updated exactly once
7011                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7012                                         panic!("Generated ChannelUpdate for wrong chan!");
7013                                 }
7014                         },
7015                         _ => panic!("Unexpected event"),
7016                 }
7017         }
7018         // Reconnect peers
7019         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7020         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7021         assert_eq!(reestablish_1.len(), 3);
7022         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7023         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7024         assert_eq!(reestablish_2.len(), 3);
7025
7026         // Reestablish chan_1
7027         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7028         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7029         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7030         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7031         // Reestablish chan_2
7032         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7033         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7034         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7035         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7036         // Reestablish chan_3
7037         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7038         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7039         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7040         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7041
7042         nodes[0].node.timer_tick_occurred();
7043         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7044         nodes[0].node.timer_tick_occurred();
7045         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7046         assert_eq!(msg_events.len(), 3);
7047         for e in msg_events {
7048                 match e {
7049                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7050                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7051                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7052                                         // Each update should have a higher timestamp than the previous one, replacing
7053                                         // the old one.
7054                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7055                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7056                                 }
7057                         },
7058                         _ => panic!("Unexpected event"),
7059                 }
7060         }
7061         // Check that each channel gets updated exactly once
7062         assert!(chans_disabled.is_empty());
7063 }
7064
7065 #[test]
7066 fn test_bump_penalty_txn_on_revoked_commitment() {
7067         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7068         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7069
7070         let chanmon_cfgs = create_chanmon_cfgs(2);
7071         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7072         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7073         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7074
7075         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7076
7077         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7078         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id())
7079                 .with_features(channelmanager::provided_invoice_features());
7080         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7081         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7082
7083         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7084         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7085         assert_eq!(revoked_txn[0].output.len(), 4);
7086         assert_eq!(revoked_txn[0].input.len(), 1);
7087         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7088         let revoked_txid = revoked_txn[0].txid();
7089
7090         let mut penalty_sum = 0;
7091         for outp in revoked_txn[0].output.iter() {
7092                 if outp.script_pubkey.is_v0_p2wsh() {
7093                         penalty_sum += outp.value;
7094                 }
7095         }
7096
7097         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7098         let header_114 = connect_blocks(&nodes[1], 14);
7099
7100         // Actually revoke tx by claiming a HTLC
7101         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7102         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7103         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7104         check_added_monitors!(nodes[1], 1);
7105
7106         // One or more justice tx should have been broadcast, check it
7107         let penalty_1;
7108         let feerate_1;
7109         {
7110                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7111                 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7112                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7113                 assert_eq!(node_txn[0].output.len(), 1);
7114                 check_spends!(node_txn[0], revoked_txn[0]);
7115                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7116                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7117                 penalty_1 = node_txn[0].txid();
7118                 node_txn.clear();
7119         };
7120
7121         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7122         connect_blocks(&nodes[1], 15);
7123         let mut penalty_2 = penalty_1;
7124         let mut feerate_2 = 0;
7125         {
7126                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7127                 assert_eq!(node_txn.len(), 1);
7128                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7129                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7130                         assert_eq!(node_txn[0].output.len(), 1);
7131                         check_spends!(node_txn[0], revoked_txn[0]);
7132                         penalty_2 = node_txn[0].txid();
7133                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7134                         assert_ne!(penalty_2, penalty_1);
7135                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7136                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7137                         // Verify 25% bump heuristic
7138                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7139                         node_txn.clear();
7140                 }
7141         }
7142         assert_ne!(feerate_2, 0);
7143
7144         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7145         connect_blocks(&nodes[1], 1);
7146         let penalty_3;
7147         let mut feerate_3 = 0;
7148         {
7149                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7150                 assert_eq!(node_txn.len(), 1);
7151                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7152                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7153                         assert_eq!(node_txn[0].output.len(), 1);
7154                         check_spends!(node_txn[0], revoked_txn[0]);
7155                         penalty_3 = node_txn[0].txid();
7156                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7157                         assert_ne!(penalty_3, penalty_2);
7158                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7159                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7160                         // Verify 25% bump heuristic
7161                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7162                         node_txn.clear();
7163                 }
7164         }
7165         assert_ne!(feerate_3, 0);
7166
7167         nodes[1].node.get_and_clear_pending_events();
7168         nodes[1].node.get_and_clear_pending_msg_events();
7169 }
7170
7171 #[test]
7172 fn test_bump_penalty_txn_on_revoked_htlcs() {
7173         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7174         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7175
7176         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7177         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7178         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7179         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7180         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7181
7182         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7183         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7184         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(channelmanager::provided_invoice_features());
7185         let scorer = test_utils::TestScorer::with_penalty(0);
7186         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7187         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7188                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7189         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7190         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(channelmanager::provided_invoice_features());
7191         let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7192                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7193         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7194
7195         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7196         assert_eq!(revoked_local_txn[0].input.len(), 1);
7197         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7198
7199         // Revoke local commitment tx
7200         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7201
7202         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7203         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7204         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7205         check_closed_broadcast!(nodes[1], true);
7206         check_added_monitors!(nodes[1], 1);
7207         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7208         connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7209
7210         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
7211         assert_eq!(revoked_htlc_txn.len(), 3);
7212         check_spends!(revoked_htlc_txn[1], chan.3);
7213
7214         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7215         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7216         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7217
7218         assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7219         assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7220         assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7221         check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7222
7223         // Broadcast set of revoked txn on A
7224         let hash_128 = connect_blocks(&nodes[0], 40);
7225         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7226         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7227         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7228         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7229         let events = nodes[0].node.get_and_clear_pending_events();
7230         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7231         match events.last().unwrap() {
7232                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7233                 _ => panic!("Unexpected event"),
7234         }
7235         let first;
7236         let feerate_1;
7237         let penalty_txn;
7238         {
7239                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7240                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7241                 // Verify claim tx are spending revoked HTLC txn
7242
7243                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7244                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7245                 // which are included in the same block (they are broadcasted because we scan the
7246                 // transactions linearly and generate claims as we go, they likely should be removed in the
7247                 // future).
7248                 assert_eq!(node_txn[0].input.len(), 1);
7249                 check_spends!(node_txn[0], revoked_local_txn[0]);
7250                 assert_eq!(node_txn[1].input.len(), 1);
7251                 check_spends!(node_txn[1], revoked_local_txn[0]);
7252                 assert_eq!(node_txn[2].input.len(), 1);
7253                 check_spends!(node_txn[2], revoked_local_txn[0]);
7254
7255                 // Each of the three justice transactions claim a separate (single) output of the three
7256                 // available, which we check here:
7257                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7258                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7259                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7260
7261                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7262                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7263
7264                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7265                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7266                 // a remote commitment tx has already been confirmed).
7267                 check_spends!(node_txn[3], chan.3);
7268
7269                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7270                 // output, checked above).
7271                 assert_eq!(node_txn[4].input.len(), 2);
7272                 assert_eq!(node_txn[4].output.len(), 1);
7273                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7274
7275                 first = node_txn[4].txid();
7276                 // Store both feerates for later comparison
7277                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7278                 feerate_1 = fee_1 * 1000 / node_txn[4].weight() as u64;
7279                 penalty_txn = vec![node_txn[2].clone()];
7280                 node_txn.clear();
7281         }
7282
7283         // Connect one more block to see if bumped penalty are issued for HTLC txn
7284         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7285         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7286         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7287         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7288
7289         // Few more blocks to confirm penalty txn
7290         connect_blocks(&nodes[0], 4);
7291         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7292         let header_144 = connect_blocks(&nodes[0], 9);
7293         let node_txn = {
7294                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7295                 assert_eq!(node_txn.len(), 1);
7296
7297                 assert_eq!(node_txn[0].input.len(), 2);
7298                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7299                 // Verify bumped tx is different and 25% bump heuristic
7300                 assert_ne!(first, node_txn[0].txid());
7301                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7302                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7303                 assert!(feerate_2 * 100 > feerate_1 * 125);
7304                 let txn = vec![node_txn[0].clone()];
7305                 node_txn.clear();
7306                 txn
7307         };
7308         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7309         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7310         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7311         connect_blocks(&nodes[0], 20);
7312         {
7313                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7314                 // We verify than no new transaction has been broadcast because previously
7315                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7316                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7317                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7318                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7319                 // up bumped justice generation.
7320                 assert_eq!(node_txn.len(), 0);
7321                 node_txn.clear();
7322         }
7323         check_closed_broadcast!(nodes[0], true);
7324         check_added_monitors!(nodes[0], 1);
7325 }
7326
7327 #[test]
7328 fn test_bump_penalty_txn_on_remote_commitment() {
7329         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7330         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7331
7332         // Create 2 HTLCs
7333         // Provide preimage for one
7334         // Check aggregation
7335
7336         let chanmon_cfgs = create_chanmon_cfgs(2);
7337         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7338         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7339         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7340
7341         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7342         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7343         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7344
7345         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7346         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7347         assert_eq!(remote_txn[0].output.len(), 4);
7348         assert_eq!(remote_txn[0].input.len(), 1);
7349         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7350
7351         // Claim a HTLC without revocation (provide B monitor with preimage)
7352         nodes[1].node.claim_funds(payment_preimage);
7353         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7354         mine_transaction(&nodes[1], &remote_txn[0]);
7355         check_added_monitors!(nodes[1], 2);
7356         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7357
7358         // One or more claim tx should have been broadcast, check it
7359         let timeout;
7360         let preimage;
7361         let preimage_bump;
7362         let feerate_timeout;
7363         let feerate_preimage;
7364         {
7365                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7366                 // 5 transactions including:
7367                 //   local commitment + HTLC-Success
7368                 //   preimage and timeout sweeps from remote commitment + preimage sweep bump
7369                 assert_eq!(node_txn.len(), 5);
7370                 assert_eq!(node_txn[0].input.len(), 1);
7371                 assert_eq!(node_txn[3].input.len(), 1);
7372                 assert_eq!(node_txn[4].input.len(), 1);
7373                 check_spends!(node_txn[0], remote_txn[0]);
7374                 check_spends!(node_txn[3], remote_txn[0]);
7375                 check_spends!(node_txn[4], remote_txn[0]);
7376
7377                 check_spends!(node_txn[1], chan.3); // local commitment
7378                 check_spends!(node_txn[2], node_txn[1]); // local HTLC-Success
7379
7380                 preimage = node_txn[0].txid();
7381                 let index = node_txn[0].input[0].previous_output.vout;
7382                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7383                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7384
7385                 let (preimage_bump_tx, timeout_tx) = if node_txn[3].input[0].previous_output == node_txn[0].input[0].previous_output {
7386                         (node_txn[3].clone(), node_txn[4].clone())
7387                 } else {
7388                         (node_txn[4].clone(), node_txn[3].clone())
7389                 };
7390
7391                 preimage_bump = preimage_bump_tx;
7392                 check_spends!(preimage_bump, remote_txn[0]);
7393                 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7394
7395                 timeout = timeout_tx.txid();
7396                 let index = timeout_tx.input[0].previous_output.vout;
7397                 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7398                 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7399
7400                 node_txn.clear();
7401         };
7402         assert_ne!(feerate_timeout, 0);
7403         assert_ne!(feerate_preimage, 0);
7404
7405         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7406         connect_blocks(&nodes[1], 15);
7407         {
7408                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7409                 assert_eq!(node_txn.len(), 1);
7410                 assert_eq!(node_txn[0].input.len(), 1);
7411                 assert_eq!(preimage_bump.input.len(), 1);
7412                 check_spends!(node_txn[0], remote_txn[0]);
7413                 check_spends!(preimage_bump, remote_txn[0]);
7414
7415                 let index = preimage_bump.input[0].previous_output.vout;
7416                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7417                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7418                 assert!(new_feerate * 100 > feerate_timeout * 125);
7419                 assert_ne!(timeout, preimage_bump.txid());
7420
7421                 let index = node_txn[0].input[0].previous_output.vout;
7422                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7423                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7424                 assert!(new_feerate * 100 > feerate_preimage * 125);
7425                 assert_ne!(preimage, node_txn[0].txid());
7426
7427                 node_txn.clear();
7428         }
7429
7430         nodes[1].node.get_and_clear_pending_events();
7431         nodes[1].node.get_and_clear_pending_msg_events();
7432 }
7433
7434 #[test]
7435 fn test_counterparty_raa_skip_no_crash() {
7436         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7437         // commitment transaction, we would have happily carried on and provided them the next
7438         // commitment transaction based on one RAA forward. This would probably eventually have led to
7439         // channel closure, but it would not have resulted in funds loss. Still, our
7440         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7441         // check simply that the channel is closed in response to such an RAA, but don't check whether
7442         // we decide to punish our counterparty for revoking their funds (as we don't currently
7443         // implement that).
7444         let chanmon_cfgs = create_chanmon_cfgs(2);
7445         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7446         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7447         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7448         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
7449
7450         let per_commitment_secret;
7451         let next_per_commitment_point;
7452         {
7453                 let mut guard = nodes[0].node.channel_state.lock().unwrap();
7454                 let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
7455
7456                 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7457
7458                 // Make signer believe we got a counterparty signature, so that it allows the revocation
7459                 keys.get_enforcement_state().last_holder_commitment -= 1;
7460                 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7461
7462                 // Must revoke without gaps
7463                 keys.get_enforcement_state().last_holder_commitment -= 1;
7464                 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7465
7466                 keys.get_enforcement_state().last_holder_commitment -= 1;
7467                 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7468                         &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7469         }
7470
7471         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7472                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7473         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7474         check_added_monitors!(nodes[1], 1);
7475         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7476 }
7477
7478 #[test]
7479 fn test_bump_txn_sanitize_tracking_maps() {
7480         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7481         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7482
7483         let chanmon_cfgs = create_chanmon_cfgs(2);
7484         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7485         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7486         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7487
7488         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7489         // Lock HTLC in both directions
7490         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7491         let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7492
7493         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7494         assert_eq!(revoked_local_txn[0].input.len(), 1);
7495         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7496
7497         // Revoke local commitment tx
7498         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7499
7500         // Broadcast set of revoked txn on A
7501         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7502         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7503         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7504
7505         mine_transaction(&nodes[0], &revoked_local_txn[0]);
7506         check_closed_broadcast!(nodes[0], true);
7507         check_added_monitors!(nodes[0], 1);
7508         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7509         let penalty_txn = {
7510                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7511                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
7512                 check_spends!(node_txn[0], revoked_local_txn[0]);
7513                 check_spends!(node_txn[1], revoked_local_txn[0]);
7514                 check_spends!(node_txn[2], revoked_local_txn[0]);
7515                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7516                 node_txn.clear();
7517                 penalty_txn
7518         };
7519         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7520         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7521         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7522         {
7523                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7524                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7525                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7526         }
7527 }
7528
7529 #[test]
7530 fn test_pending_claimed_htlc_no_balance_underflow() {
7531         // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
7532         // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
7533         let chanmon_cfgs = create_chanmon_cfgs(2);
7534         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7535         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7536         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7537         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7538
7539         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
7540         nodes[1].node.claim_funds(payment_preimage);
7541         expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
7542         check_added_monitors!(nodes[1], 1);
7543         let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7544
7545         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
7546         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
7547         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
7548         check_added_monitors!(nodes[0], 1);
7549         let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7550
7551         // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
7552         // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
7553         // can get our balance.
7554
7555         // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
7556         // the public key of the only hop. This works around ChannelDetails not showing the
7557         // almost-claimed HTLC as available balance.
7558         let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
7559         route.payment_params = None; // This is all wrong, but unnecessary
7560         route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
7561         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
7562         nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
7563
7564         assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
7565 }
7566
7567 #[test]
7568 fn test_channel_conf_timeout() {
7569         // Tests that, for inbound channels, we give up on them if the funding transaction does not
7570         // confirm within 2016 blocks, as recommended by BOLT 2.
7571         let chanmon_cfgs = create_chanmon_cfgs(2);
7572         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7573         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7574         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7575
7576         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7577
7578         // The outbound node should wait forever for confirmation:
7579         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7580         // copied here instead of directly referencing the constant.
7581         connect_blocks(&nodes[0], 2016);
7582         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7583
7584         // The inbound node should fail the channel after exactly 2016 blocks
7585         connect_blocks(&nodes[1], 2015);
7586         check_added_monitors!(nodes[1], 0);
7587         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7588
7589         connect_blocks(&nodes[1], 1);
7590         check_added_monitors!(nodes[1], 1);
7591         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
7592         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7593         assert_eq!(close_ev.len(), 1);
7594         match close_ev[0] {
7595                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7596                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7597                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7598                 },
7599                 _ => panic!("Unexpected event"),
7600         }
7601 }
7602
7603 #[test]
7604 fn test_override_channel_config() {
7605         let chanmon_cfgs = create_chanmon_cfgs(2);
7606         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7607         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7608         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7609
7610         // Node0 initiates a channel to node1 using the override config.
7611         let mut override_config = UserConfig::default();
7612         override_config.channel_handshake_config.our_to_self_delay = 200;
7613
7614         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7615
7616         // Assert the channel created by node0 is using the override config.
7617         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7618         assert_eq!(res.channel_flags, 0);
7619         assert_eq!(res.to_self_delay, 200);
7620 }
7621
7622 #[test]
7623 fn test_override_0msat_htlc_minimum() {
7624         let mut zero_config = UserConfig::default();
7625         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
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, Some(zero_config.clone())]);
7629         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7630
7631         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7632         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7633         assert_eq!(res.htlc_minimum_msat, 1);
7634
7635         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
7636         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7637         assert_eq!(res.htlc_minimum_msat, 1);
7638 }
7639
7640 #[test]
7641 fn test_channel_update_has_correct_htlc_maximum_msat() {
7642         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7643         // Bolt 7 specifies that if present `htlc_maximum_msat`:
7644         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7645         // 90% of the `channel_value`.
7646         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7647
7648         let mut config_30_percent = UserConfig::default();
7649         config_30_percent.channel_handshake_config.announced_channel = true;
7650         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7651         let mut config_50_percent = UserConfig::default();
7652         config_50_percent.channel_handshake_config.announced_channel = true;
7653         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7654         let mut config_95_percent = UserConfig::default();
7655         config_95_percent.channel_handshake_config.announced_channel = true;
7656         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7657         let mut config_100_percent = UserConfig::default();
7658         config_100_percent.channel_handshake_config.announced_channel = true;
7659         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7660
7661         let chanmon_cfgs = create_chanmon_cfgs(4);
7662         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7663         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)]);
7664         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7665
7666         let channel_value_satoshis = 100000;
7667         let channel_value_msat = channel_value_satoshis * 1000;
7668         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7669         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7670         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7671
7672         let (node_0_chan_update, node_1_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7673         let (node_2_chan_update, node_3_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7674
7675         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7676         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7677         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7678         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7679         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7680         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7681
7682         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7683         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7684         // `channel_value`.
7685         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7686         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7687         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7688         // `channel_value`.
7689         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7690 }
7691
7692 #[test]
7693 fn test_manually_accept_inbound_channel_request() {
7694         let mut manually_accept_conf = UserConfig::default();
7695         manually_accept_conf.manually_accept_inbound_channels = true;
7696         let chanmon_cfgs = create_chanmon_cfgs(2);
7697         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7698         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7699         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7700
7701         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7702         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7703
7704         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
7705
7706         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7707         // accepting the inbound channel request.
7708         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7709
7710         let events = nodes[1].node.get_and_clear_pending_events();
7711         match events[0] {
7712                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7713                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7714                 }
7715                 _ => panic!("Unexpected event"),
7716         }
7717
7718         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7719         assert_eq!(accept_msg_ev.len(), 1);
7720
7721         match accept_msg_ev[0] {
7722                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7723                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7724                 }
7725                 _ => panic!("Unexpected event"),
7726         }
7727
7728         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7729
7730         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7731         assert_eq!(close_msg_ev.len(), 1);
7732
7733         let events = nodes[1].node.get_and_clear_pending_events();
7734         match events[0] {
7735                 Event::ChannelClosed { user_channel_id, .. } => {
7736                         assert_eq!(user_channel_id, 23);
7737                 }
7738                 _ => panic!("Unexpected event"),
7739         }
7740 }
7741
7742 #[test]
7743 fn test_manually_reject_inbound_channel_request() {
7744         let mut manually_accept_conf = UserConfig::default();
7745         manually_accept_conf.manually_accept_inbound_channels = true;
7746         let chanmon_cfgs = create_chanmon_cfgs(2);
7747         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7748         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7749         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7750
7751         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7752         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7753
7754         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
7755
7756         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7757         // rejecting the inbound channel request.
7758         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7759
7760         let events = nodes[1].node.get_and_clear_pending_events();
7761         match events[0] {
7762                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7763                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7764                 }
7765                 _ => panic!("Unexpected event"),
7766         }
7767
7768         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7769         assert_eq!(close_msg_ev.len(), 1);
7770
7771         match close_msg_ev[0] {
7772                 MessageSendEvent::HandleError { ref node_id, .. } => {
7773                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7774                 }
7775                 _ => panic!("Unexpected event"),
7776         }
7777         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
7778 }
7779
7780 #[test]
7781 fn test_reject_funding_before_inbound_channel_accepted() {
7782         // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
7783         // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
7784         // the node operator before the counterparty sends a `FundingCreated` message. If a
7785         // `FundingCreated` message is received before the channel is accepted, it should be rejected
7786         // and the channel should be closed.
7787         let mut manually_accept_conf = UserConfig::default();
7788         manually_accept_conf.manually_accept_inbound_channels = true;
7789         let chanmon_cfgs = create_chanmon_cfgs(2);
7790         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7791         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7792         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7793
7794         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7795         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7796         let temp_channel_id = res.temporary_channel_id;
7797
7798         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
7799
7800         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
7801         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7802
7803         // Clear the `Event::OpenChannelRequest` event without responding to the request.
7804         nodes[1].node.get_and_clear_pending_events();
7805
7806         // Get the `AcceptChannel` message of `nodes[1]` without calling
7807         // `ChannelManager::accept_inbound_channel`, which generates a
7808         // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
7809         // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
7810         // succeed when `nodes[0]` is passed to it.
7811         let accept_chan_msg = {
7812                 let mut lock;
7813                 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
7814                 channel.get_accept_channel_message()
7815         };
7816         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_chan_msg);
7817
7818         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
7819
7820         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
7821         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
7822
7823         // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
7824         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
7825
7826         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7827         assert_eq!(close_msg_ev.len(), 1);
7828
7829         let expected_err = "FundingCreated message received before the channel was accepted";
7830         match close_msg_ev[0] {
7831                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
7832                         assert_eq!(msg.channel_id, temp_channel_id);
7833                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7834                         assert_eq!(msg.data, expected_err);
7835                 }
7836                 _ => panic!("Unexpected event"),
7837         }
7838
7839         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
7840 }
7841
7842 #[test]
7843 fn test_can_not_accept_inbound_channel_twice() {
7844         let mut manually_accept_conf = UserConfig::default();
7845         manually_accept_conf.manually_accept_inbound_channels = true;
7846         let chanmon_cfgs = create_chanmon_cfgs(2);
7847         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7848         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7849         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7850
7851         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7852         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7853
7854         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
7855
7856         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7857         // accepting the inbound channel request.
7858         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7859
7860         let events = nodes[1].node.get_and_clear_pending_events();
7861         match events[0] {
7862                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7863                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7864                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7865                         match api_res {
7866                                 Err(APIError::APIMisuseError { err }) => {
7867                                         assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
7868                                 },
7869                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7870                                 Err(_) => panic!("Unexpected Error"),
7871                         }
7872                 }
7873                 _ => panic!("Unexpected event"),
7874         }
7875
7876         // Ensure that the channel wasn't closed after attempting to accept it twice.
7877         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7878         assert_eq!(accept_msg_ev.len(), 1);
7879
7880         match accept_msg_ev[0] {
7881                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7882                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7883                 }
7884                 _ => panic!("Unexpected event"),
7885         }
7886 }
7887
7888 #[test]
7889 fn test_can_not_accept_unknown_inbound_channel() {
7890         let chanmon_cfg = create_chanmon_cfgs(2);
7891         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
7892         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
7893         let nodes = create_network(2, &node_cfg, &node_chanmgr);
7894
7895         let unknown_channel_id = [0; 32];
7896         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
7897         match api_res {
7898                 Err(APIError::ChannelUnavailable { err }) => {
7899                         assert_eq!(err, "Can't accept a channel that doesn't exist");
7900                 },
7901                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
7902                 Err(_) => panic!("Unexpected Error"),
7903         }
7904 }
7905
7906 #[test]
7907 fn test_simple_mpp() {
7908         // Simple test of sending a multi-path payment.
7909         let chanmon_cfgs = create_chanmon_cfgs(4);
7910         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7911         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
7912         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7913
7914         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
7915         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
7916         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
7917         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
7918
7919         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
7920         let path = route.paths[0].clone();
7921         route.paths.push(path);
7922         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
7923         route.paths[0][0].short_channel_id = chan_1_id;
7924         route.paths[0][1].short_channel_id = chan_3_id;
7925         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
7926         route.paths[1][0].short_channel_id = chan_2_id;
7927         route.paths[1][1].short_channel_id = chan_4_id;
7928         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
7929         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
7930 }
7931
7932 #[test]
7933 fn test_preimage_storage() {
7934         // Simple test of payment preimage storage allowing no client-side storage to claim payments
7935         let chanmon_cfgs = create_chanmon_cfgs(2);
7936         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7937         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7938         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7939
7940         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
7941
7942         {
7943                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
7944                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
7945                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
7946                 check_added_monitors!(nodes[0], 1);
7947                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7948                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7949                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7950                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7951         }
7952         // Note that after leaving the above scope we have no knowledge of any arguments or return
7953         // values from previous calls.
7954         expect_pending_htlcs_forwardable!(nodes[1]);
7955         let events = nodes[1].node.get_and_clear_pending_events();
7956         assert_eq!(events.len(), 1);
7957         match events[0] {
7958                 Event::PaymentClaimable { ref purpose, .. } => {
7959                         match &purpose {
7960                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
7961                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
7962                                 },
7963                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
7964                         }
7965                 },
7966                 _ => panic!("Unexpected event"),
7967         }
7968 }
7969
7970 #[test]
7971 #[allow(deprecated)]
7972 fn test_secret_timeout() {
7973         // Simple test of payment secret storage time outs. After
7974         // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
7975         let chanmon_cfgs = create_chanmon_cfgs(2);
7976         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7977         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7978         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7979
7980         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
7981
7982         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
7983
7984         // We should fail to register the same payment hash twice, at least until we've connected a
7985         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
7986         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
7987                 assert_eq!(err, "Duplicate payment hash");
7988         } else { panic!(); }
7989         let mut block = {
7990                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
7991                 Block {
7992                         header: BlockHeader {
7993                                 version: 0x2000000,
7994                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
7995                                 merkle_root: TxMerkleNode::all_zeros(),
7996                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
7997                         txdata: vec![],
7998                 }
7999         };
8000         connect_block(&nodes[1], &block);
8001         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8002                 assert_eq!(err, "Duplicate payment hash");
8003         } else { panic!(); }
8004
8005         // If we then connect the second block, we should be able to register the same payment hash
8006         // again (this time getting a new payment secret).
8007         block.header.prev_blockhash = block.header.block_hash();
8008         block.header.time += 1;
8009         connect_block(&nodes[1], &block);
8010         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8011         assert_ne!(payment_secret_1, our_payment_secret);
8012
8013         {
8014                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8015                 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret), PaymentId(payment_hash.0)).unwrap();
8016                 check_added_monitors!(nodes[0], 1);
8017                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8018                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8019                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8020                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8021         }
8022         // Note that after leaving the above scope we have no knowledge of any arguments or return
8023         // values from previous calls.
8024         expect_pending_htlcs_forwardable!(nodes[1]);
8025         let events = nodes[1].node.get_and_clear_pending_events();
8026         assert_eq!(events.len(), 1);
8027         match events[0] {
8028                 Event::PaymentClaimable { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8029                         assert!(payment_preimage.is_none());
8030                         assert_eq!(payment_secret, our_payment_secret);
8031                         // We don't actually have the payment preimage with which to claim this payment!
8032                 },
8033                 _ => panic!("Unexpected event"),
8034         }
8035 }
8036
8037 #[test]
8038 fn test_bad_secret_hash() {
8039         // Simple test of unregistered payment hash/invalid payment secret handling
8040         let chanmon_cfgs = create_chanmon_cfgs(2);
8041         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8042         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8043         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8044
8045         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
8046
8047         let random_payment_hash = PaymentHash([42; 32]);
8048         let random_payment_secret = PaymentSecret([43; 32]);
8049         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8050         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8051
8052         // All the below cases should end up being handled exactly identically, so we macro the
8053         // resulting events.
8054         macro_rules! handle_unknown_invalid_payment_data {
8055                 ($payment_hash: expr) => {
8056                         check_added_monitors!(nodes[0], 1);
8057                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8058                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8059                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8060                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8061
8062                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8063                         // again to process the pending backwards-failure of the HTLC
8064                         expect_pending_htlcs_forwardable!(nodes[1]);
8065                         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8066                         check_added_monitors!(nodes[1], 1);
8067
8068                         // We should fail the payment back
8069                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8070                         match events.pop().unwrap() {
8071                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8072                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8073                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8074                                 },
8075                                 _ => panic!("Unexpected event"),
8076                         }
8077                 }
8078         }
8079
8080         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8081         // Error data is the HTLC value (100,000) and current block height
8082         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8083
8084         // Send a payment with the right payment hash but the wrong payment secret
8085         nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8086         handle_unknown_invalid_payment_data!(our_payment_hash);
8087         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8088
8089         // Send a payment with a random payment hash, but the right payment secret
8090         nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8091         handle_unknown_invalid_payment_data!(random_payment_hash);
8092         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8093
8094         // Send a payment with a random payment hash and random payment secret
8095         nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8096         handle_unknown_invalid_payment_data!(random_payment_hash);
8097         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8098 }
8099
8100 #[test]
8101 fn test_update_err_monitor_lockdown() {
8102         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8103         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8104         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8105         // error.
8106         //
8107         // This scenario may happen in a watchtower setup, where watchtower process a block height
8108         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8109         // commitment at same time.
8110
8111         let chanmon_cfgs = create_chanmon_cfgs(2);
8112         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8113         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8114         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8115
8116         // Create some initial channel
8117         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8118         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8119
8120         // Rebalance the network to generate htlc in the two directions
8121         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8122
8123         // Route a HTLC from node 0 to node 1 (but don't settle)
8124         let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8125
8126         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8127         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8128         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8129         let persister = test_utils::TestPersister::new();
8130         let watchtower = {
8131                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8132                 let mut w = test_utils::TestVecWriter(Vec::new());
8133                 monitor.write(&mut w).unwrap();
8134                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8135                                 &mut io::Cursor::new(&w.0), nodes[0].keys_manager).unwrap().1;
8136                 assert!(new_monitor == *monitor);
8137                 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);
8138                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8139                 watchtower
8140         };
8141         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8142         let block = Block { header, txdata: vec![] };
8143         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8144         // transaction lock time requirements here.
8145         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8146         watchtower.chain_monitor.block_connected(&block, 200);
8147
8148         // Try to update ChannelMonitor
8149         nodes[1].node.claim_funds(preimage);
8150         check_added_monitors!(nodes[1], 1);
8151         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8152
8153         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8154         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8155         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8156         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8157                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8158                         assert_eq!(watchtower.chain_monitor.update_channel(outpoint, update.clone()), ChannelMonitorUpdateStatus::PermanentFailure);
8159                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, update), ChannelMonitorUpdateStatus::Completed);
8160                 } else { assert!(false); }
8161         } else { assert!(false); };
8162         // Our local monitor is in-sync and hasn't processed yet timeout
8163         check_added_monitors!(nodes[0], 1);
8164         let events = nodes[0].node.get_and_clear_pending_events();
8165         assert_eq!(events.len(), 1);
8166 }
8167
8168 #[test]
8169 fn test_concurrent_monitor_claim() {
8170         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8171         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8172         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8173         // state N+1 confirms. Alice claims output from state N+1.
8174
8175         let chanmon_cfgs = create_chanmon_cfgs(2);
8176         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8177         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8178         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8179
8180         // Create some initial channel
8181         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8182         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8183
8184         // Rebalance the network to generate htlc in the two directions
8185         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8186
8187         // Route a HTLC from node 0 to node 1 (but don't settle)
8188         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8189
8190         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8191         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8192         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8193         let persister = test_utils::TestPersister::new();
8194         let watchtower_alice = {
8195                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8196                 let mut w = test_utils::TestVecWriter(Vec::new());
8197                 monitor.write(&mut w).unwrap();
8198                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8199                                 &mut io::Cursor::new(&w.0), nodes[0].keys_manager).unwrap().1;
8200                 assert!(new_monitor == *monitor);
8201                 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);
8202                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8203                 watchtower
8204         };
8205         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8206         let block = Block { header, txdata: vec![] };
8207         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8208         // transaction lock time requirements here.
8209         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));
8210         watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8211
8212         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8213         {
8214                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8215                 assert_eq!(txn.len(), 2);
8216                 txn.clear();
8217         }
8218
8219         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8220         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8221         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8222         let persister = test_utils::TestPersister::new();
8223         let watchtower_bob = {
8224                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8225                 let mut w = test_utils::TestVecWriter(Vec::new());
8226                 monitor.write(&mut w).unwrap();
8227                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8228                                 &mut io::Cursor::new(&w.0), nodes[0].keys_manager).unwrap().1;
8229                 assert!(new_monitor == *monitor);
8230                 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);
8231                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8232                 watchtower
8233         };
8234         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8235         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8236
8237         // Route another payment to generate another update with still previous HTLC pending
8238         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8239         {
8240                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
8241         }
8242         check_added_monitors!(nodes[1], 1);
8243
8244         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8245         assert_eq!(updates.update_add_htlcs.len(), 1);
8246         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8247         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8248                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8249                         // Watchtower Alice should already have seen the block and reject the update
8250                         assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()), ChannelMonitorUpdateStatus::PermanentFailure);
8251                         assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()), ChannelMonitorUpdateStatus::Completed);
8252                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, update), ChannelMonitorUpdateStatus::Completed);
8253                 } else { assert!(false); }
8254         } else { assert!(false); };
8255         // Our local monitor is in-sync and hasn't processed yet timeout
8256         check_added_monitors!(nodes[0], 1);
8257
8258         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8259         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8260         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8261
8262         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8263         let bob_state_y;
8264         {
8265                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8266                 assert_eq!(txn.len(), 2);
8267                 bob_state_y = txn[0].clone();
8268                 txn.clear();
8269         };
8270
8271         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8272         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8273         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);
8274         {
8275                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8276                 assert_eq!(htlc_txn.len(), 1);
8277                 check_spends!(htlc_txn[0], bob_state_y);
8278         }
8279 }
8280
8281 #[test]
8282 fn test_pre_lockin_no_chan_closed_update() {
8283         // Test that if a peer closes a channel in response to a funding_created message we don't
8284         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8285         // message).
8286         //
8287         // Doing so would imply a channel monitor update before the initial channel monitor
8288         // registration, violating our API guarantees.
8289         //
8290         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8291         // then opening a second channel with the same funding output as the first (which is not
8292         // rejected because the first channel does not exist in the ChannelManager) and closing it
8293         // before receiving funding_signed.
8294         let chanmon_cfgs = create_chanmon_cfgs(2);
8295         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8296         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8297         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8298
8299         // Create an initial channel
8300         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8301         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8302         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
8303         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8304         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_chan_msg);
8305
8306         // Move the first channel through the funding flow...
8307         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8308
8309         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8310         check_added_monitors!(nodes[0], 0);
8311
8312         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8313         let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8314         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8315         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8316         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8317 }
8318
8319 #[test]
8320 fn test_htlc_no_detection() {
8321         // This test is a mutation to underscore the detection logic bug we had
8322         // before #653. HTLC value routed is above the remaining balance, thus
8323         // inverting HTLC and `to_remote` output. HTLC will come second and
8324         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8325         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8326         // outputs order detection for correct spending children filtring.
8327
8328         let chanmon_cfgs = create_chanmon_cfgs(2);
8329         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8330         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8331         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8332
8333         // Create some initial channels
8334         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8335
8336         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8337         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8338         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8339         assert_eq!(local_txn[0].input.len(), 1);
8340         assert_eq!(local_txn[0].output.len(), 3);
8341         check_spends!(local_txn[0], chan_1.3);
8342
8343         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8344         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8345         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8346         // We deliberately connect the local tx twice as this should provoke a failure calling
8347         // this test before #653 fix.
8348         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);
8349         check_closed_broadcast!(nodes[0], true);
8350         check_added_monitors!(nodes[0], 1);
8351         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8352         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8353
8354         let htlc_timeout = {
8355                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8356                 assert_eq!(node_txn[1].input.len(), 1);
8357                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8358                 check_spends!(node_txn[1], local_txn[0]);
8359                 node_txn[1].clone()
8360         };
8361
8362         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8363         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8364         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8365         expect_payment_failed!(nodes[0], our_payment_hash, false);
8366 }
8367
8368 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8369         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8370         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8371         // Carol, Alice would be the upstream node, and Carol the downstream.)
8372         //
8373         // Steps of the test:
8374         // 1) Alice sends a HTLC to Carol through Bob.
8375         // 2) Carol doesn't settle the HTLC.
8376         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8377         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8378         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8379         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8380         // 5) Carol release the preimage to Bob off-chain.
8381         // 6) Bob claims the offered output on the broadcasted commitment.
8382         let chanmon_cfgs = create_chanmon_cfgs(3);
8383         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8384         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8385         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8386
8387         // Create some initial channels
8388         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8389         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8390
8391         // Steps (1) and (2):
8392         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8393         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8394
8395         // Check that Alice's commitment transaction now contains an output for this HTLC.
8396         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8397         check_spends!(alice_txn[0], chan_ab.3);
8398         assert_eq!(alice_txn[0].output.len(), 2);
8399         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8400         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8401         assert_eq!(alice_txn.len(), 2);
8402
8403         // Steps (3) and (4):
8404         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8405         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8406         let mut force_closing_node = 0; // Alice force-closes
8407         let mut counterparty_node = 1; // Bob if Alice force-closes
8408
8409         // Bob force-closes
8410         if !broadcast_alice {
8411                 force_closing_node = 1;
8412                 counterparty_node = 0;
8413         }
8414         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8415         check_closed_broadcast!(nodes[force_closing_node], true);
8416         check_added_monitors!(nodes[force_closing_node], 1);
8417         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8418         if go_onchain_before_fulfill {
8419                 let txn_to_broadcast = match broadcast_alice {
8420                         true => alice_txn.clone(),
8421                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8422                 };
8423                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8424                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8425                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8426                 if broadcast_alice {
8427                         check_closed_broadcast!(nodes[1], true);
8428                         check_added_monitors!(nodes[1], 1);
8429                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8430                 }
8431                 assert_eq!(bob_txn.len(), 1);
8432                 check_spends!(bob_txn[0], chan_ab.3);
8433         }
8434
8435         // Step (5):
8436         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8437         // process of removing the HTLC from their commitment transactions.
8438         nodes[2].node.claim_funds(payment_preimage);
8439         check_added_monitors!(nodes[2], 1);
8440         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8441
8442         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8443         assert!(carol_updates.update_add_htlcs.is_empty());
8444         assert!(carol_updates.update_fail_htlcs.is_empty());
8445         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8446         assert!(carol_updates.update_fee.is_none());
8447         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8448
8449         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8450         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8451         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8452         if !go_onchain_before_fulfill && broadcast_alice {
8453                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8454                 assert_eq!(events.len(), 1);
8455                 match events[0] {
8456                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8457                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8458                         },
8459                         _ => panic!("Unexpected event"),
8460                 };
8461         }
8462         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8463         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8464         // Carol<->Bob's updated commitment transaction info.
8465         check_added_monitors!(nodes[1], 2);
8466
8467         let events = nodes[1].node.get_and_clear_pending_msg_events();
8468         assert_eq!(events.len(), 2);
8469         let bob_revocation = match events[0] {
8470                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8471                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8472                         (*msg).clone()
8473                 },
8474                 _ => panic!("Unexpected event"),
8475         };
8476         let bob_updates = match events[1] {
8477                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8478                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8479                         (*updates).clone()
8480                 },
8481                 _ => panic!("Unexpected event"),
8482         };
8483
8484         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8485         check_added_monitors!(nodes[2], 1);
8486         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8487         check_added_monitors!(nodes[2], 1);
8488
8489         let events = nodes[2].node.get_and_clear_pending_msg_events();
8490         assert_eq!(events.len(), 1);
8491         let carol_revocation = match events[0] {
8492                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8493                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8494                         (*msg).clone()
8495                 },
8496                 _ => panic!("Unexpected event"),
8497         };
8498         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8499         check_added_monitors!(nodes[1], 1);
8500
8501         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8502         // here's where we put said channel's commitment tx on-chain.
8503         let mut txn_to_broadcast = alice_txn.clone();
8504         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8505         if !go_onchain_before_fulfill {
8506                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8507                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8508                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8509                 if broadcast_alice {
8510                         check_closed_broadcast!(nodes[1], true);
8511                         check_added_monitors!(nodes[1], 1);
8512                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8513                 }
8514                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8515                 if broadcast_alice {
8516                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8517                         // new block being connected. The ChannelManager being notified triggers a monitor update,
8518                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8519                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8520                         // broadcasted.
8521                         assert_eq!(bob_txn.len(), 3);
8522                         check_spends!(bob_txn[1], chan_ab.3);
8523                 } else {
8524                         assert_eq!(bob_txn.len(), 2);
8525                         check_spends!(bob_txn[0], chan_ab.3);
8526                 }
8527         }
8528
8529         // Step (6):
8530         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8531         // broadcasted commitment transaction.
8532         {
8533                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8534                 if go_onchain_before_fulfill {
8535                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8536                         assert_eq!(bob_txn.len(), 2);
8537                 }
8538                 let script_weight = match broadcast_alice {
8539                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8540                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8541                 };
8542                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8543                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8544                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8545                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8546                 if broadcast_alice && !go_onchain_before_fulfill {
8547                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8548                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8549                 } else {
8550                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8551                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8552                 }
8553         }
8554 }
8555
8556 #[test]
8557 fn test_onchain_htlc_settlement_after_close() {
8558         do_test_onchain_htlc_settlement_after_close(true, true);
8559         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8560         do_test_onchain_htlc_settlement_after_close(true, false);
8561         do_test_onchain_htlc_settlement_after_close(false, false);
8562 }
8563
8564 #[test]
8565 fn test_duplicate_chan_id() {
8566         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8567         // already open we reject it and keep the old channel.
8568         //
8569         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8570         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8571         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8572         // updating logic for the existing channel.
8573         let chanmon_cfgs = create_chanmon_cfgs(2);
8574         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8575         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8576         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8577
8578         // Create an initial channel
8579         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8580         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8581         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
8582         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
8583
8584         // Try to create a second channel with the same temporary_channel_id as the first and check
8585         // that it is rejected.
8586         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
8587         {
8588                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8589                 assert_eq!(events.len(), 1);
8590                 match events[0] {
8591                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8592                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8593                                 // first (valid) and second (invalid) channels are closed, given they both have
8594                                 // the same non-temporary channel_id. However, currently we do not, so we just
8595                                 // move forward with it.
8596                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8597                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8598                         },
8599                         _ => panic!("Unexpected event"),
8600                 }
8601         }
8602
8603         // Move the first channel through the funding flow...
8604         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8605
8606         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8607         check_added_monitors!(nodes[0], 0);
8608
8609         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8610         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8611         {
8612                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8613                 assert_eq!(added_monitors.len(), 1);
8614                 assert_eq!(added_monitors[0].0, funding_output);
8615                 added_monitors.clear();
8616         }
8617         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8618
8619         let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8620         let channel_id = funding_outpoint.to_channel_id();
8621
8622         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8623         // temporary one).
8624
8625         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8626         // Technically this is allowed by the spec, but we don't support it and there's little reason
8627         // to. Still, it shouldn't cause any other issues.
8628         open_chan_msg.temporary_channel_id = channel_id;
8629         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
8630         {
8631                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8632                 assert_eq!(events.len(), 1);
8633                 match events[0] {
8634                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8635                                 // Technically, at this point, nodes[1] would be justified in thinking both
8636                                 // channels are closed, but currently we do not, so we just move forward with it.
8637                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8638                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8639                         },
8640                         _ => panic!("Unexpected event"),
8641                 }
8642         }
8643
8644         // Now try to create a second channel which has a duplicate funding output.
8645         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8646         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8647         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_2_msg);
8648         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
8649         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8650
8651         let funding_created = {
8652                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8653                 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
8654                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8655                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8656                 // channelmanager in a possibly nonsense state instead).
8657                 let mut as_chan = a_channel_lock.by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8658                 let logger = test_utils::TestLogger::new();
8659                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8660         };
8661         check_added_monitors!(nodes[0], 0);
8662         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8663         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8664         // still needs to be cleared here.
8665         check_added_monitors!(nodes[1], 1);
8666
8667         // ...still, nodes[1] will reject the duplicate channel.
8668         {
8669                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8670                 assert_eq!(events.len(), 1);
8671                 match events[0] {
8672                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8673                                 // Technically, at this point, nodes[1] would be justified in thinking both
8674                                 // channels are closed, but currently we do not, so we just move forward with it.
8675                                 assert_eq!(msg.channel_id, channel_id);
8676                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8677                         },
8678                         _ => panic!("Unexpected event"),
8679                 }
8680         }
8681
8682         // finally, finish creating the original channel and send a payment over it to make sure
8683         // everything is functional.
8684         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8685         {
8686                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8687                 assert_eq!(added_monitors.len(), 1);
8688                 assert_eq!(added_monitors[0].0, funding_output);
8689                 added_monitors.clear();
8690         }
8691
8692         let events_4 = nodes[0].node.get_and_clear_pending_events();
8693         assert_eq!(events_4.len(), 0);
8694         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8695         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8696
8697         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8698         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
8699         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8700
8701         send_payment(&nodes[0], &[&nodes[1]], 8000000);
8702 }
8703
8704 #[test]
8705 fn test_error_chans_closed() {
8706         // Test that we properly handle error messages, closing appropriate channels.
8707         //
8708         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8709         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8710         // we can test various edge cases around it to ensure we don't regress.
8711         let chanmon_cfgs = create_chanmon_cfgs(3);
8712         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8713         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8714         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8715
8716         // Create some initial channels
8717         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8718         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8719         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8720
8721         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8722         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8723         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8724
8725         // Closing a channel from a different peer has no effect
8726         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8727         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8728
8729         // Closing one channel doesn't impact others
8730         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8731         check_added_monitors!(nodes[0], 1);
8732         check_closed_broadcast!(nodes[0], false);
8733         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
8734         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8735         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8736         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);
8737         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);
8738
8739         // A null channel ID should close all channels
8740         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8741         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8742         check_added_monitors!(nodes[0], 2);
8743         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
8744         let events = nodes[0].node.get_and_clear_pending_msg_events();
8745         assert_eq!(events.len(), 2);
8746         match events[0] {
8747                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8748                         assert_eq!(msg.contents.flags & 2, 2);
8749                 },
8750                 _ => panic!("Unexpected event"),
8751         }
8752         match events[1] {
8753                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8754                         assert_eq!(msg.contents.flags & 2, 2);
8755                 },
8756                 _ => panic!("Unexpected event"),
8757         }
8758         // Note that at this point users of a standard PeerHandler will end up calling
8759         // peer_disconnected with no_connection_possible set to false, duplicating the
8760         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
8761         // users with their own peer handling logic. We duplicate the call here, however.
8762         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8763         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8764
8765         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
8766         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8767         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8768 }
8769
8770 #[test]
8771 fn test_invalid_funding_tx() {
8772         // Test that we properly handle invalid funding transactions sent to us from a peer.
8773         //
8774         // Previously, all other major lightning implementations had failed to properly sanitize
8775         // funding transactions from their counterparties, leading to a multi-implementation critical
8776         // security vulnerability (though we always sanitized properly, we've previously had
8777         // un-released crashes in the sanitization process).
8778         //
8779         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
8780         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
8781         // gave up on it. We test this here by generating such a transaction.
8782         let chanmon_cfgs = create_chanmon_cfgs(2);
8783         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8784         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8785         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8786
8787         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
8788         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
8789         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
8790
8791         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
8792
8793         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
8794         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
8795         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
8796         // its length.
8797         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
8798         let wit_program_script: Script = wit_program.into();
8799         for output in tx.output.iter_mut() {
8800                 // Make the confirmed funding transaction have a bogus script_pubkey
8801                 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
8802         }
8803
8804         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
8805         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()));
8806         check_added_monitors!(nodes[1], 1);
8807
8808         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()));
8809         check_added_monitors!(nodes[0], 1);
8810
8811         let events_1 = nodes[0].node.get_and_clear_pending_events();
8812         assert_eq!(events_1.len(), 0);
8813
8814         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8815         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8816         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
8817
8818         let expected_err = "funding tx had wrong script/value or output index";
8819         confirm_transaction_at(&nodes[1], &tx, 1);
8820         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8821         check_added_monitors!(nodes[1], 1);
8822         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
8823         assert_eq!(events_2.len(), 1);
8824         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
8825                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8826                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
8827                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
8828                 } else { panic!(); }
8829         } else { panic!(); }
8830         assert_eq!(nodes[1].node.list_channels().len(), 0);
8831
8832         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
8833         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
8834         // as its not 32 bytes long.
8835         let mut spend_tx = Transaction {
8836                 version: 2i32, lock_time: PackedLockTime::ZERO,
8837                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
8838                         previous_output: BitcoinOutPoint {
8839                                 txid: tx.txid(),
8840                                 vout: idx as u32,
8841                         },
8842                         script_sig: Script::new(),
8843                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
8844                         witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
8845                 }).collect(),
8846                 output: vec![TxOut {
8847                         value: 1000,
8848                         script_pubkey: Script::new(),
8849                 }]
8850         };
8851         check_spends!(spend_tx, tx);
8852         mine_transaction(&nodes[1], &spend_tx);
8853 }
8854
8855 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
8856         // In the first version of the chain::Confirm interface, after a refactor was made to not
8857         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
8858         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
8859         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
8860         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
8861         // spending transaction until height N+1 (or greater). This was due to the way
8862         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
8863         // spending transaction at the height the input transaction was confirmed at, not whether we
8864         // should broadcast a spending transaction at the current height.
8865         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
8866         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
8867         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
8868         // until we learned about an additional block.
8869         //
8870         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
8871         // aren't broadcasting transactions too early (ie not broadcasting them at all).
8872         let chanmon_cfgs = create_chanmon_cfgs(3);
8873         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8874         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8875         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8876         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
8877
8878         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8879         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8880         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
8881         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
8882         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8883
8884         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
8885         check_closed_broadcast!(nodes[1], true);
8886         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8887         check_added_monitors!(nodes[1], 1);
8888         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
8889         assert_eq!(node_txn.len(), 1);
8890
8891         let conf_height = nodes[1].best_block_info().1;
8892         if !test_height_before_timelock {
8893                 connect_blocks(&nodes[1], 24 * 6);
8894         }
8895         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
8896                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
8897         if test_height_before_timelock {
8898                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
8899                 // generate any events or broadcast any transactions
8900                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
8901                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
8902         } else {
8903                 // We should broadcast an HTLC transaction spending our funding transaction first
8904                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
8905                 assert_eq!(spending_txn.len(), 2);
8906                 assert_eq!(spending_txn[0], node_txn[0]);
8907                 check_spends!(spending_txn[1], node_txn[0]);
8908                 // We should also generate a SpendableOutputs event with the to_self output (as its
8909                 // timelock is up).
8910                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
8911                 assert_eq!(descriptor_spend_txn.len(), 1);
8912
8913                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
8914                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
8915                 // additional block built on top of the current chain.
8916                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
8917                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
8918                 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 }]);
8919                 check_added_monitors!(nodes[1], 1);
8920
8921                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8922                 assert!(updates.update_add_htlcs.is_empty());
8923                 assert!(updates.update_fulfill_htlcs.is_empty());
8924                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8925                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8926                 assert!(updates.update_fee.is_none());
8927                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
8928                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
8929                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
8930         }
8931 }
8932
8933 #[test]
8934 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
8935         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
8936         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
8937 }
8938
8939 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
8940         let chanmon_cfgs = create_chanmon_cfgs(2);
8941         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8942         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8943         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8944
8945         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8946
8947         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
8948                 .with_features(channelmanager::provided_invoice_features());
8949         let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
8950
8951         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
8952
8953         {
8954                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8955                 check_added_monitors!(nodes[0], 1);
8956                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8957                 assert_eq!(events.len(), 1);
8958                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8959                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8960                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8961         }
8962         expect_pending_htlcs_forwardable!(nodes[1]);
8963         expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
8964
8965         {
8966                 // Note that we use a different PaymentId here to allow us to duplicativly pay
8967                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
8968                 check_added_monitors!(nodes[0], 1);
8969                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8970                 assert_eq!(events.len(), 1);
8971                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8972                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8973                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8974                 // At this point, nodes[1] would notice it has too much value for the payment. It will
8975                 // assume the second is a privacy attack (no longer particularly relevant
8976                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
8977                 // the first HTLC delivered above.
8978         }
8979
8980         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
8981         nodes[1].node.process_pending_htlc_forwards();
8982
8983         if test_for_second_fail_panic {
8984                 // Now we go fail back the first HTLC from the user end.
8985                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
8986
8987                 let expected_destinations = vec![
8988                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
8989                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
8990                 ];
8991                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],  expected_destinations);
8992                 nodes[1].node.process_pending_htlc_forwards();
8993
8994                 check_added_monitors!(nodes[1], 1);
8995                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8996                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
8997
8998                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
8999                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9000                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9001
9002                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9003                 assert_eq!(failure_events.len(), 2);
9004                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9005                 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9006         } else {
9007                 // Let the second HTLC fail and claim the first
9008                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9009                 nodes[1].node.process_pending_htlc_forwards();
9010
9011                 check_added_monitors!(nodes[1], 1);
9012                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9013                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9014                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9015
9016                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9017
9018                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9019         }
9020 }
9021
9022 #[test]
9023 fn test_dup_htlc_second_fail_panic() {
9024         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9025         // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9026         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9027         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9028         do_test_dup_htlc_second_rejected(true);
9029 }
9030
9031 #[test]
9032 fn test_dup_htlc_second_rejected() {
9033         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9034         // simply reject the second HTLC but are still able to claim the first HTLC.
9035         do_test_dup_htlc_second_rejected(false);
9036 }
9037
9038 #[test]
9039 fn test_inconsistent_mpp_params() {
9040         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9041         // such HTLC and allow the second to stay.
9042         let chanmon_cfgs = create_chanmon_cfgs(4);
9043         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9044         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9045         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9046
9047         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9048         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9049         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9050         let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9051
9052         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
9053                 .with_features(channelmanager::provided_invoice_features());
9054         let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9055         assert_eq!(route.paths.len(), 2);
9056         route.paths.sort_by(|path_a, _| {
9057                 // Sort the path so that the path through nodes[1] comes first
9058                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9059                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9060         });
9061         let payment_params_opt = Some(payment_params);
9062
9063         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9064
9065         let cur_height = nodes[0].best_block_info().1;
9066         let payment_id = PaymentId([42; 32]);
9067
9068         let session_privs = {
9069                 // We create a fake route here so that we start with three pending HTLCs, which we'll
9070                 // ultimately have, just not right away.
9071                 let mut dup_route = route.clone();
9072                 dup_route.paths.push(route.paths[1].clone());
9073                 nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(our_payment_secret), payment_id, &dup_route).unwrap()
9074         };
9075         {
9076                 nodes[0].node.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();
9077                 check_added_monitors!(nodes[0], 1);
9078
9079                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9080                 assert_eq!(events.len(), 1);
9081                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9082         }
9083         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9084
9085         {
9086                 nodes[0].node.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();
9087                 check_added_monitors!(nodes[0], 1);
9088
9089                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9090                 assert_eq!(events.len(), 1);
9091                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9092
9093                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9094                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9095
9096                 expect_pending_htlcs_forwardable!(nodes[2]);
9097                 check_added_monitors!(nodes[2], 1);
9098
9099                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9100                 assert_eq!(events.len(), 1);
9101                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9102
9103                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9104                 check_added_monitors!(nodes[3], 0);
9105                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9106
9107                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9108                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9109                 // post-payment_secrets) and fail back the new HTLC.
9110         }
9111         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9112         nodes[3].node.process_pending_htlc_forwards();
9113         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9114         nodes[3].node.process_pending_htlc_forwards();
9115
9116         check_added_monitors!(nodes[3], 1);
9117
9118         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9119         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9120         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9121
9122         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 }]);
9123         check_added_monitors!(nodes[2], 1);
9124
9125         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9126         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9127         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9128
9129         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9130
9131         nodes[0].node.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();
9132         check_added_monitors!(nodes[0], 1);
9133
9134         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9135         assert_eq!(events.len(), 1);
9136         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9137
9138         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9139 }
9140
9141 #[test]
9142 fn test_keysend_payments_to_public_node() {
9143         let chanmon_cfgs = create_chanmon_cfgs(2);
9144         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9145         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9146         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9147
9148         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9149         let network_graph = nodes[0].network_graph;
9150         let payer_pubkey = nodes[0].node.get_our_node_id();
9151         let payee_pubkey = nodes[1].node.get_our_node_id();
9152         let route_params = RouteParameters {
9153                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9154                 final_value_msat: 10000,
9155                 final_cltv_expiry_delta: 40,
9156         };
9157         let scorer = test_utils::TestScorer::with_penalty(0);
9158         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9159         let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9160
9161         let test_preimage = PaymentPreimage([42; 32]);
9162         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage), PaymentId(test_preimage.0)).unwrap();
9163         check_added_monitors!(nodes[0], 1);
9164         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9165         assert_eq!(events.len(), 1);
9166         let event = events.pop().unwrap();
9167         let path = vec![&nodes[1]];
9168         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9169         claim_payment(&nodes[0], &path, test_preimage);
9170 }
9171
9172 #[test]
9173 fn test_keysend_payments_to_private_node() {
9174         let chanmon_cfgs = create_chanmon_cfgs(2);
9175         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9176         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9177         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9178
9179         let payer_pubkey = nodes[0].node.get_our_node_id();
9180         let payee_pubkey = nodes[1].node.get_our_node_id();
9181         nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
9182         nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
9183
9184         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], channelmanager::provided_init_features(), channelmanager::provided_init_features());
9185         let route_params = RouteParameters {
9186                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9187                 final_value_msat: 10000,
9188                 final_cltv_expiry_delta: 40,
9189         };
9190         let network_graph = nodes[0].network_graph;
9191         let first_hops = nodes[0].node.list_usable_channels();
9192         let scorer = test_utils::TestScorer::with_penalty(0);
9193         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9194         let route = find_route(
9195                 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9196                 nodes[0].logger, &scorer, &random_seed_bytes
9197         ).unwrap();
9198
9199         let test_preimage = PaymentPreimage([42; 32]);
9200         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage), PaymentId(test_preimage.0)).unwrap();
9201         check_added_monitors!(nodes[0], 1);
9202         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9203         assert_eq!(events.len(), 1);
9204         let event = events.pop().unwrap();
9205         let path = vec![&nodes[1]];
9206         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9207         claim_payment(&nodes[0], &path, test_preimage);
9208 }
9209
9210 #[test]
9211 fn test_double_partial_claim() {
9212         // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9213         // time out, the sender resends only some of the MPP parts, then the user processes the
9214         // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9215         // amount.
9216         let chanmon_cfgs = create_chanmon_cfgs(4);
9217         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9218         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9219         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9220
9221         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9222         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9223         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9224         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9225
9226         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9227         assert_eq!(route.paths.len(), 2);
9228         route.paths.sort_by(|path_a, _| {
9229                 // Sort the path so that the path through nodes[1] comes first
9230                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9231                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9232         });
9233
9234         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9235         // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9236         // amount of time to respond to.
9237
9238         // Connect some blocks to time out the payment
9239         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9240         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9241
9242         let failed_destinations = vec![
9243                 HTLCDestination::FailedPayment { payment_hash },
9244                 HTLCDestination::FailedPayment { payment_hash },
9245         ];
9246         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9247
9248         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
9249
9250         // nodes[1] now retries one of the two paths...
9251         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9252         check_added_monitors!(nodes[0], 2);
9253
9254         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9255         assert_eq!(events.len(), 2);
9256         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
9257
9258         // At this point nodes[3] has received one half of the payment, and the user goes to handle
9259         // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9260         nodes[3].node.claim_funds(payment_preimage);
9261         check_added_monitors!(nodes[3], 0);
9262         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9263 }
9264
9265 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9266 #[derive(Clone, Copy, PartialEq)]
9267 enum ExposureEvent {
9268         /// Breach occurs at HTLC forwarding (see `send_htlc`)
9269         AtHTLCForward,
9270         /// Breach occurs at HTLC reception (see `update_add_htlc`)
9271         AtHTLCReception,
9272         /// Breach occurs at outbound update_fee (see `send_update_fee`)
9273         AtUpdateFeeOutbound,
9274 }
9275
9276 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9277         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9278         // policy.
9279         //
9280         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9281         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9282         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9283         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9284         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9285         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9286         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9287         // might be available again for HTLC processing once the dust bandwidth has cleared up.
9288
9289         let chanmon_cfgs = create_chanmon_cfgs(2);
9290         let mut config = test_default_channel_config();
9291         config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9292         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9293         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9294         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9295
9296         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9297         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9298         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9299         open_channel.max_accepted_htlcs = 60;
9300         if on_holder_tx {
9301                 open_channel.dust_limit_satoshis = 546;
9302         }
9303         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
9304         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9305         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
9306
9307         let opt_anchors = false;
9308
9309         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9310
9311         if on_holder_tx {
9312                 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
9313                         chan.holder_dust_limit_satoshis = 546;
9314                 }
9315         }
9316
9317         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9318         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()));
9319         check_added_monitors!(nodes[1], 1);
9320
9321         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()));
9322         check_added_monitors!(nodes[0], 1);
9323
9324         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9325         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9326         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9327
9328         let dust_buffer_feerate = {
9329                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
9330                 let chan = chan_lock.by_id.get(&channel_id).unwrap();
9331                 chan.get_dust_buffer_feerate(None) as u64
9332         };
9333         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;
9334         let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9335
9336         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;
9337         let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9338
9339         let dust_htlc_on_counterparty_tx: u64 = 25;
9340         let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9341
9342         if on_holder_tx {
9343                 if dust_outbound_balance {
9344                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9345                         // Outbound dust balance: 4372 sats
9346                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9347                         for i in 0..dust_outbound_htlc_on_holder_tx {
9348                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9349                                 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); }
9350                         }
9351                 } else {
9352                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9353                         // Inbound dust balance: 4372 sats
9354                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9355                         for _ in 0..dust_inbound_htlc_on_holder_tx {
9356                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9357                         }
9358                 }
9359         } else {
9360                 if dust_outbound_balance {
9361                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9362                         // Outbound dust balance: 5000 sats
9363                         for i in 0..dust_htlc_on_counterparty_tx {
9364                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9365                                 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); }
9366                         }
9367                 } else {
9368                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9369                         // Inbound dust balance: 5000 sats
9370                         for _ in 0..dust_htlc_on_counterparty_tx {
9371                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9372                         }
9373                 }
9374         }
9375
9376         let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9377         if exposure_breach_event == ExposureEvent::AtHTLCForward {
9378                 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 });
9379                 let mut config = UserConfig::default();
9380                 // With default dust exposure: 5000 sats
9381                 if on_holder_tx {
9382                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9383                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9384                         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)));
9385                 } else {
9386                         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)));
9387                 }
9388         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9389                 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 });
9390                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9391                 check_added_monitors!(nodes[1], 1);
9392                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9393                 assert_eq!(events.len(), 1);
9394                 let payment_event = SendEvent::from_event(events.remove(0));
9395                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9396                 // With default dust exposure: 5000 sats
9397                 if on_holder_tx {
9398                         // Outbound dust balance: 6399 sats
9399                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9400                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9401                         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);
9402                 } else {
9403                         // Outbound dust balance: 5200 sats
9404                         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);
9405                 }
9406         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9407                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
9408                 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", ); }
9409                 {
9410                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9411                         *feerate_lock = *feerate_lock * 10;
9412                 }
9413                 nodes[0].node.timer_tick_occurred();
9414                 check_added_monitors!(nodes[0], 1);
9415                 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);
9416         }
9417
9418         let _ = nodes[0].node.get_and_clear_pending_msg_events();
9419         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9420         added_monitors.clear();
9421 }
9422
9423 #[test]
9424 fn test_max_dust_htlc_exposure() {
9425         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9426         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9427         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9428         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9429         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9430         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9431         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9432         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9433         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9434         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9435         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9436         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
9437 }
9438
9439 #[test]
9440 fn test_non_final_funding_tx() {
9441         let chanmon_cfgs = create_chanmon_cfgs(2);
9442         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9443         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9444         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9445
9446         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9447         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9448         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel_message);
9449         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9450         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel_message);
9451
9452         let best_height = nodes[0].node.best_block.read().unwrap().height();
9453
9454         let chan_id = *nodes[0].network_chan_count.borrow();
9455         let events = nodes[0].node.get_and_clear_pending_events();
9456         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9457         assert_eq!(events.len(), 1);
9458         let mut tx = match events[0] {
9459                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9460                         // Timelock the transaction _beyond_ the best client height + 2.
9461                         Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 3), input: vec![input], output: vec![TxOut {
9462                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9463                         }]}
9464                 },
9465                 _ => panic!("Unexpected event"),
9466         };
9467         // Transaction should fail as it's evaluated as non-final for propagation.
9468         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9469                 Err(APIError::APIMisuseError { err }) => {
9470                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9471                 },
9472                 _ => panic!()
9473         }
9474
9475         // However, transaction should be accepted if it's in a +2 headroom from best block.
9476         tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9477         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9478         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9479 }
9480
9481 #[test]
9482 fn accept_busted_but_better_fee() {
9483         // If a peer sends us a fee update that is too low, but higher than our previous channel
9484         // feerate, we should accept it. In the future we may want to consider closing the channel
9485         // later, but for now we only accept the update.
9486         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9487         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9488         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9489         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9490
9491         create_chan_between_nodes(&nodes[0], &nodes[1], channelmanager::provided_init_features(), channelmanager::provided_init_features());
9492
9493         // Set nodes[1] to expect 5,000 sat/kW.
9494         {
9495                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9496                 *feerate_lock = 5000;
9497         }
9498
9499         // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9500         {
9501                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9502                 *feerate_lock = 1000;
9503         }
9504         nodes[0].node.timer_tick_occurred();
9505         check_added_monitors!(nodes[0], 1);
9506
9507         let events = nodes[0].node.get_and_clear_pending_msg_events();
9508         assert_eq!(events.len(), 1);
9509         match events[0] {
9510                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9511                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9512                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9513                 },
9514                 _ => panic!("Unexpected event"),
9515         };
9516
9517         // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9518         // it.
9519         {
9520                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9521                 *feerate_lock = 2000;
9522         }
9523         nodes[0].node.timer_tick_occurred();
9524         check_added_monitors!(nodes[0], 1);
9525
9526         let events = nodes[0].node.get_and_clear_pending_msg_events();
9527         assert_eq!(events.len(), 1);
9528         match events[0] {
9529                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9530                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9531                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9532                 },
9533                 _ => panic!("Unexpected event"),
9534         };
9535
9536         // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9537         // channel.
9538         {
9539                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9540                 *feerate_lock = 1000;
9541         }
9542         nodes[0].node.timer_tick_occurred();
9543         check_added_monitors!(nodes[0], 1);
9544
9545         let events = nodes[0].node.get_and_clear_pending_msg_events();
9546         assert_eq!(events.len(), 1);
9547         match events[0] {
9548                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9549                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9550                         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9551                                 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() });
9552                         check_closed_broadcast!(nodes[1], true);
9553                         check_added_monitors!(nodes[1], 1);
9554                 },
9555                 _ => panic!("Unexpected event"),
9556         };
9557 }