adds 'receiver_node_id' to 'Event::Payment{Received,Claimed}'
[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::{byte_utils, 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).unwrap();
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::PaymentReceived { .. } => { },
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::PaymentReceived { 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).unwrap();
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_received!(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::PaymentReceived { ref payment_hash, ref purpose, amount_msat, receiver_node_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                         match &purpose {
1964                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1965                                         assert!(payment_preimage.is_none());
1966                                         assert_eq!(our_payment_secret_21, *payment_secret);
1967                                 },
1968                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1969                         }
1970                 },
1971                 _ => panic!("Unexpected event"),
1972         }
1973         match events[1] {
1974                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat, receiver_node_id } => {
1975                         assert_eq!(our_payment_hash_22, *payment_hash);
1976                         assert_eq!(recv_value_22, amount_msat);
1977                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
1978                         match &purpose {
1979                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1980                                         assert!(payment_preimage.is_none());
1981                                         assert_eq!(our_payment_secret_22, *payment_secret);
1982                                 },
1983                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1984                         }
1985                 },
1986                 _ => panic!("Unexpected event"),
1987         }
1988
1989         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1990         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1991         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
1992
1993         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
1994         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
1995         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
1996
1997         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
1998         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);
1999         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2000         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2001         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2002
2003         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2004         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2005 }
2006
2007 #[test]
2008 fn channel_reserve_in_flight_removes() {
2009         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2010         // can send to its counterparty, but due to update ordering, the other side may not yet have
2011         // considered those HTLCs fully removed.
2012         // This tests that we don't count HTLCs which will not be included in the next remote
2013         // commitment transaction towards the reserve value (as it implies no commitment transaction
2014         // will be generated which violates the remote reserve value).
2015         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2016         // To test this we:
2017         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2018         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2019         //    you only consider the value of the first HTLC, it may not),
2020         //  * start routing a third HTLC from A to B,
2021         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2022         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2023         //  * deliver the first fulfill from B
2024         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2025         //    claim,
2026         //  * deliver A's response CS and RAA.
2027         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2028         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2029         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2030         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2031         let chanmon_cfgs = create_chanmon_cfgs(2);
2032         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2033         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2034         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2035         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2036
2037         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2038         // Route the first two HTLCs.
2039         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2040         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2041         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2042
2043         // Start routing the third HTLC (this is just used to get everyone in the right state).
2044         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2045         let send_1 = {
2046                 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2047                 check_added_monitors!(nodes[0], 1);
2048                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2049                 assert_eq!(events.len(), 1);
2050                 SendEvent::from_event(events.remove(0))
2051         };
2052
2053         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2054         // initial fulfill/CS.
2055         nodes[1].node.claim_funds(payment_preimage_1);
2056         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2057         check_added_monitors!(nodes[1], 1);
2058         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2059
2060         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2061         // remove the second HTLC when we send the HTLC back from B to A.
2062         nodes[1].node.claim_funds(payment_preimage_2);
2063         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2064         check_added_monitors!(nodes[1], 1);
2065         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2066
2067         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2068         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2069         check_added_monitors!(nodes[0], 1);
2070         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2071         expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2072
2073         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2074         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2075         check_added_monitors!(nodes[1], 1);
2076         // B is already AwaitingRAA, so cant generate a CS here
2077         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2078
2079         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2080         check_added_monitors!(nodes[1], 1);
2081         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2082
2083         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2084         check_added_monitors!(nodes[0], 1);
2085         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2086
2087         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2088         check_added_monitors!(nodes[1], 1);
2089         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2090
2091         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2092         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2093         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2094         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2095         // on-chain as necessary).
2096         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2097         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2098         check_added_monitors!(nodes[0], 1);
2099         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2100         expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2101
2102         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2103         check_added_monitors!(nodes[1], 1);
2104         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2105
2106         expect_pending_htlcs_forwardable!(nodes[1]);
2107         expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2108
2109         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2110         // resolve the second HTLC from A's point of view.
2111         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2112         check_added_monitors!(nodes[0], 1);
2113         expect_payment_path_successful!(nodes[0]);
2114         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2115
2116         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2117         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2118         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2119         let send_2 = {
2120                 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2121                 check_added_monitors!(nodes[1], 1);
2122                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2123                 assert_eq!(events.len(), 1);
2124                 SendEvent::from_event(events.remove(0))
2125         };
2126
2127         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2128         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2129         check_added_monitors!(nodes[0], 1);
2130         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2131
2132         // Now just resolve all the outstanding messages/HTLCs for completeness...
2133
2134         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2135         check_added_monitors!(nodes[1], 1);
2136         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2137
2138         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2139         check_added_monitors!(nodes[1], 1);
2140
2141         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2142         check_added_monitors!(nodes[0], 1);
2143         expect_payment_path_successful!(nodes[0]);
2144         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2145
2146         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2147         check_added_monitors!(nodes[1], 1);
2148         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2149
2150         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2151         check_added_monitors!(nodes[0], 1);
2152
2153         expect_pending_htlcs_forwardable!(nodes[0]);
2154         expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2155
2156         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2157         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2158 }
2159
2160 #[test]
2161 fn channel_monitor_network_test() {
2162         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2163         // tests that ChannelMonitor is able to recover from various states.
2164         let chanmon_cfgs = create_chanmon_cfgs(5);
2165         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2166         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2167         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2168
2169         // Create some initial channels
2170         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2171         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2172         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2173         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2174
2175         // Make sure all nodes are at the same starting height
2176         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2177         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2178         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2179         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2180         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2181
2182         // Rebalance the network a bit by relaying one payment through all the channels...
2183         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2184         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
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
2188         // Simple case with no pending HTLCs:
2189         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2190         check_added_monitors!(nodes[1], 1);
2191         check_closed_broadcast!(nodes[1], true);
2192         {
2193                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2194                 assert_eq!(node_txn.len(), 1);
2195                 mine_transaction(&nodes[0], &node_txn[0]);
2196                 check_added_monitors!(nodes[0], 1);
2197                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2198         }
2199         check_closed_broadcast!(nodes[0], true);
2200         assert_eq!(nodes[0].node.list_channels().len(), 0);
2201         assert_eq!(nodes[1].node.list_channels().len(), 1);
2202         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2203         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2204
2205         // One pending HTLC is discarded by the force-close:
2206         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2207
2208         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2209         // broadcasted until we reach the timelock time).
2210         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2211         check_closed_broadcast!(nodes[1], true);
2212         check_added_monitors!(nodes[1], 1);
2213         {
2214                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2215                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2216                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2217                 mine_transaction(&nodes[2], &node_txn[0]);
2218                 check_added_monitors!(nodes[2], 1);
2219                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2220         }
2221         check_closed_broadcast!(nodes[2], true);
2222         assert_eq!(nodes[1].node.list_channels().len(), 0);
2223         assert_eq!(nodes[2].node.list_channels().len(), 1);
2224         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2225         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2226
2227         macro_rules! claim_funds {
2228                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2229                         {
2230                                 $node.node.claim_funds($preimage);
2231                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2232                                 check_added_monitors!($node, 1);
2233
2234                                 let events = $node.node.get_and_clear_pending_msg_events();
2235                                 assert_eq!(events.len(), 1);
2236                                 match events[0] {
2237                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2238                                                 assert!(update_add_htlcs.is_empty());
2239                                                 assert!(update_fail_htlcs.is_empty());
2240                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2241                                         },
2242                                         _ => panic!("Unexpected event"),
2243                                 };
2244                         }
2245                 }
2246         }
2247
2248         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2249         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2250         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2251         check_added_monitors!(nodes[2], 1);
2252         check_closed_broadcast!(nodes[2], true);
2253         let node2_commitment_txid;
2254         {
2255                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2256                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2257                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2258                 node2_commitment_txid = node_txn[0].txid();
2259
2260                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2261                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2262                 mine_transaction(&nodes[3], &node_txn[0]);
2263                 check_added_monitors!(nodes[3], 1);
2264                 check_preimage_claim(&nodes[3], &node_txn);
2265         }
2266         check_closed_broadcast!(nodes[3], true);
2267         assert_eq!(nodes[2].node.list_channels().len(), 0);
2268         assert_eq!(nodes[3].node.list_channels().len(), 1);
2269         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2270         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2271
2272         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2273         // confusing us in the following tests.
2274         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2275
2276         // One pending HTLC to time out:
2277         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2278         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2279         // buffer space).
2280
2281         let (close_chan_update_1, close_chan_update_2) = {
2282                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2283                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2284                 assert_eq!(events.len(), 2);
2285                 let close_chan_update_1 = match events[0] {
2286                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2287                                 msg.clone()
2288                         },
2289                         _ => panic!("Unexpected event"),
2290                 };
2291                 match events[1] {
2292                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2293                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2294                         },
2295                         _ => panic!("Unexpected event"),
2296                 }
2297                 check_added_monitors!(nodes[3], 1);
2298
2299                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2300                 {
2301                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2302                         node_txn.retain(|tx| {
2303                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2304                                         false
2305                                 } else { true }
2306                         });
2307                 }
2308
2309                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2310
2311                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2312                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2313
2314                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2315                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2316                 assert_eq!(events.len(), 2);
2317                 let close_chan_update_2 = match events[0] {
2318                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2319                                 msg.clone()
2320                         },
2321                         _ => panic!("Unexpected event"),
2322                 };
2323                 match events[1] {
2324                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2325                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2326                         },
2327                         _ => panic!("Unexpected event"),
2328                 }
2329                 check_added_monitors!(nodes[4], 1);
2330                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2331
2332                 mine_transaction(&nodes[4], &node_txn[0]);
2333                 check_preimage_claim(&nodes[4], &node_txn);
2334                 (close_chan_update_1, close_chan_update_2)
2335         };
2336         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2337         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2338         assert_eq!(nodes[3].node.list_channels().len(), 0);
2339         assert_eq!(nodes[4].node.list_channels().len(), 0);
2340
2341         assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2342                 ChannelMonitorUpdateStatus::Completed);
2343         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2344         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2345 }
2346
2347 #[test]
2348 fn test_justice_tx() {
2349         // Test justice txn built on revoked HTLC-Success tx, against both sides
2350         let mut alice_config = UserConfig::default();
2351         alice_config.channel_handshake_config.announced_channel = true;
2352         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2353         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2354         let mut bob_config = UserConfig::default();
2355         bob_config.channel_handshake_config.announced_channel = true;
2356         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2357         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2358         let user_cfgs = [Some(alice_config), Some(bob_config)];
2359         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2360         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2361         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2362         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2363         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2364         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2365         *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2366         // Create some new channels:
2367         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2368
2369         // A pending HTLC which will be revoked:
2370         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2371         // Get the will-be-revoked local txn from nodes[0]
2372         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2373         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2374         assert_eq!(revoked_local_txn[0].input.len(), 1);
2375         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2376         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2377         assert_eq!(revoked_local_txn[1].input.len(), 1);
2378         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2379         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2380         // Revoke the old state
2381         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2382
2383         {
2384                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2385                 {
2386                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2387                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2388                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2389
2390                         check_spends!(node_txn[0], revoked_local_txn[0]);
2391                         node_txn.swap_remove(0);
2392                         node_txn.truncate(1);
2393                 }
2394                 check_added_monitors!(nodes[1], 1);
2395                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2396                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2397
2398                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2399                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2400                 // Verify broadcast of revoked HTLC-timeout
2401                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2402                 check_added_monitors!(nodes[0], 1);
2403                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2404                 // Broadcast revoked HTLC-timeout on node 1
2405                 mine_transaction(&nodes[1], &node_txn[1]);
2406                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2407         }
2408         get_announce_close_broadcast_events(&nodes, 0, 1);
2409
2410         assert_eq!(nodes[0].node.list_channels().len(), 0);
2411         assert_eq!(nodes[1].node.list_channels().len(), 0);
2412
2413         // We test justice_tx build by A on B's revoked HTLC-Success tx
2414         // Create some new channels:
2415         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2416         {
2417                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2418                 node_txn.clear();
2419         }
2420
2421         // A pending HTLC which will be revoked:
2422         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2423         // Get the will-be-revoked local txn from B
2424         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2425         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2426         assert_eq!(revoked_local_txn[0].input.len(), 1);
2427         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2428         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2429         // Revoke the old state
2430         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2431         {
2432                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2433                 {
2434                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2435                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2436                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2437
2438                         check_spends!(node_txn[0], revoked_local_txn[0]);
2439                         node_txn.swap_remove(0);
2440                 }
2441                 check_added_monitors!(nodes[0], 1);
2442                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2443
2444                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2445                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2446                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2447                 check_added_monitors!(nodes[1], 1);
2448                 mine_transaction(&nodes[0], &node_txn[1]);
2449                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2450                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2451         }
2452         get_announce_close_broadcast_events(&nodes, 0, 1);
2453         assert_eq!(nodes[0].node.list_channels().len(), 0);
2454         assert_eq!(nodes[1].node.list_channels().len(), 0);
2455 }
2456
2457 #[test]
2458 fn revoked_output_claim() {
2459         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2460         // transaction is broadcast by its counterparty
2461         let chanmon_cfgs = create_chanmon_cfgs(2);
2462         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2463         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2464         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2465         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2466         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2467         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2468         assert_eq!(revoked_local_txn.len(), 1);
2469         // Only output is the full channel value back to nodes[0]:
2470         assert_eq!(revoked_local_txn[0].output.len(), 1);
2471         // Send a payment through, updating everyone's latest commitment txn
2472         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2473
2474         // Inform nodes[1] that nodes[0] broadcast a stale tx
2475         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2476         check_added_monitors!(nodes[1], 1);
2477         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2478         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2479         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2480
2481         check_spends!(node_txn[0], revoked_local_txn[0]);
2482         check_spends!(node_txn[1], chan_1.3);
2483
2484         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2485         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2486         get_announce_close_broadcast_events(&nodes, 0, 1);
2487         check_added_monitors!(nodes[0], 1);
2488         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2489 }
2490
2491 #[test]
2492 fn claim_htlc_outputs_shared_tx() {
2493         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2494         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2495         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2496         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2497         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2498         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2499
2500         // Create some new channel:
2501         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2502
2503         // Rebalance the network to generate htlc in the two directions
2504         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2505         // 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
2506         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2507         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2508
2509         // Get the will-be-revoked local txn from node[0]
2510         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2511         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2512         assert_eq!(revoked_local_txn[0].input.len(), 1);
2513         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2514         assert_eq!(revoked_local_txn[1].input.len(), 1);
2515         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2516         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2517         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2518
2519         //Revoke the old state
2520         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2521
2522         {
2523                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2524                 check_added_monitors!(nodes[0], 1);
2525                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2526                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2527                 check_added_monitors!(nodes[1], 1);
2528                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2529                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2530                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2531
2532                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2533                 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2534
2535                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2536                 check_spends!(node_txn[0], revoked_local_txn[0]);
2537
2538                 let mut witness_lens = BTreeSet::new();
2539                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2540                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2541                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2542                 assert_eq!(witness_lens.len(), 3);
2543                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2544                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2545                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2546
2547                 // Next nodes[1] broadcasts its current local tx state:
2548                 assert_eq!(node_txn[1].input.len(), 1);
2549                 check_spends!(node_txn[1], chan_1.3);
2550
2551                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2552                 // ANTI_REORG_DELAY confirmations.
2553                 mine_transaction(&nodes[1], &node_txn[0]);
2554                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2555                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2556         }
2557         get_announce_close_broadcast_events(&nodes, 0, 1);
2558         assert_eq!(nodes[0].node.list_channels().len(), 0);
2559         assert_eq!(nodes[1].node.list_channels().len(), 0);
2560 }
2561
2562 #[test]
2563 fn claim_htlc_outputs_single_tx() {
2564         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2565         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2566         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2567         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2568         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2569         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2570
2571         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2572
2573         // Rebalance the network to generate htlc in the two directions
2574         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2575         // 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
2576         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2577         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2578         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2579
2580         // Get the will-be-revoked local txn from node[0]
2581         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2582
2583         //Revoke the old state
2584         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2585
2586         {
2587                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2588                 check_added_monitors!(nodes[0], 1);
2589                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2590                 check_added_monitors!(nodes[1], 1);
2591                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2592                 let mut events = nodes[0].node.get_and_clear_pending_events();
2593                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2594                 match events.last().unwrap() {
2595                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2596                         _ => panic!("Unexpected event"),
2597                 }
2598
2599                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2600                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2601
2602                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2603                 assert!(node_txn.len() == 9 || node_txn.len() == 10);
2604
2605                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2606                 assert_eq!(node_txn[0].input.len(), 1);
2607                 check_spends!(node_txn[0], chan_1.3);
2608                 assert_eq!(node_txn[1].input.len(), 1);
2609                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2610                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2611                 check_spends!(node_txn[1], node_txn[0]);
2612
2613                 // Justice transactions are indices 1-2-4
2614                 assert_eq!(node_txn[2].input.len(), 1);
2615                 assert_eq!(node_txn[3].input.len(), 1);
2616                 assert_eq!(node_txn[4].input.len(), 1);
2617
2618                 check_spends!(node_txn[2], revoked_local_txn[0]);
2619                 check_spends!(node_txn[3], revoked_local_txn[0]);
2620                 check_spends!(node_txn[4], revoked_local_txn[0]);
2621
2622                 let mut witness_lens = BTreeSet::new();
2623                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2624                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2625                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2626                 assert_eq!(witness_lens.len(), 3);
2627                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2628                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2629                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2630
2631                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2632                 // ANTI_REORG_DELAY confirmations.
2633                 mine_transaction(&nodes[1], &node_txn[2]);
2634                 mine_transaction(&nodes[1], &node_txn[3]);
2635                 mine_transaction(&nodes[1], &node_txn[4]);
2636                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2637                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2638         }
2639         get_announce_close_broadcast_events(&nodes, 0, 1);
2640         assert_eq!(nodes[0].node.list_channels().len(), 0);
2641         assert_eq!(nodes[1].node.list_channels().len(), 0);
2642 }
2643
2644 #[test]
2645 fn test_htlc_on_chain_success() {
2646         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2647         // the preimage backward accordingly. So here we test that ChannelManager is
2648         // broadcasting the right event to other nodes in payment path.
2649         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2650         // A --------------------> B ----------------------> C (preimage)
2651         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2652         // commitment transaction was broadcast.
2653         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2654         // towards B.
2655         // B should be able to claim via preimage if A then broadcasts its local tx.
2656         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2657         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2658         // PaymentSent event).
2659
2660         let chanmon_cfgs = create_chanmon_cfgs(3);
2661         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2662         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2663         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2664
2665         // Create some initial channels
2666         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2667         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2668
2669         // Ensure all nodes are at the same height
2670         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2671         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2672         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2673         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2674
2675         // Rebalance the network a bit by relaying one payment through all the channels...
2676         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2677         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2678
2679         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2680         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2681
2682         // Broadcast legit commitment tx from C on B's chain
2683         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2684         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2685         assert_eq!(commitment_tx.len(), 1);
2686         check_spends!(commitment_tx[0], chan_2.3);
2687         nodes[2].node.claim_funds(our_payment_preimage);
2688         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2689         nodes[2].node.claim_funds(our_payment_preimage_2);
2690         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2691         check_added_monitors!(nodes[2], 2);
2692         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2693         assert!(updates.update_add_htlcs.is_empty());
2694         assert!(updates.update_fail_htlcs.is_empty());
2695         assert!(updates.update_fail_malformed_htlcs.is_empty());
2696         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2697
2698         mine_transaction(&nodes[2], &commitment_tx[0]);
2699         check_closed_broadcast!(nodes[2], true);
2700         check_added_monitors!(nodes[2], 1);
2701         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2702         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)
2703         assert_eq!(node_txn.len(), 5);
2704         assert_eq!(node_txn[0], node_txn[3]);
2705         assert_eq!(node_txn[1], node_txn[4]);
2706         assert_eq!(node_txn[2], commitment_tx[0]);
2707         check_spends!(node_txn[0], commitment_tx[0]);
2708         check_spends!(node_txn[1], commitment_tx[0]);
2709         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2710         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2711         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2712         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2713         assert_eq!(node_txn[0].lock_time.0, 0);
2714         assert_eq!(node_txn[1].lock_time.0, 0);
2715
2716         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2717         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2718         connect_block(&nodes[1], &Block { header, txdata: node_txn});
2719         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2720         {
2721                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2722                 assert_eq!(added_monitors.len(), 1);
2723                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2724                 added_monitors.clear();
2725         }
2726         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2727         assert_eq!(forwarded_events.len(), 3);
2728         match forwarded_events[0] {
2729                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2730                 _ => panic!("Unexpected event"),
2731         }
2732         let chan_id = Some(chan_1.2);
2733         match forwarded_events[1] {
2734                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2735                         assert_eq!(fee_earned_msat, Some(1000));
2736                         assert_eq!(prev_channel_id, chan_id);
2737                         assert_eq!(claim_from_onchain_tx, true);
2738                         assert_eq!(next_channel_id, Some(chan_2.2));
2739                 },
2740                 _ => panic!()
2741         }
2742         match forwarded_events[2] {
2743                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2744                         assert_eq!(fee_earned_msat, Some(1000));
2745                         assert_eq!(prev_channel_id, chan_id);
2746                         assert_eq!(claim_from_onchain_tx, true);
2747                         assert_eq!(next_channel_id, Some(chan_2.2));
2748                 },
2749                 _ => panic!()
2750         }
2751         let events = nodes[1].node.get_and_clear_pending_msg_events();
2752         {
2753                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2754                 assert_eq!(added_monitors.len(), 2);
2755                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2756                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2757                 added_monitors.clear();
2758         }
2759         assert_eq!(events.len(), 3);
2760         match events[0] {
2761                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2762                 _ => panic!("Unexpected event"),
2763         }
2764         match events[1] {
2765                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2766                 _ => panic!("Unexpected event"),
2767         }
2768
2769         match events[2] {
2770                 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, .. } } => {
2771                         assert!(update_add_htlcs.is_empty());
2772                         assert!(update_fail_htlcs.is_empty());
2773                         assert_eq!(update_fulfill_htlcs.len(), 1);
2774                         assert!(update_fail_malformed_htlcs.is_empty());
2775                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2776                 },
2777                 _ => panic!("Unexpected event"),
2778         };
2779         macro_rules! check_tx_local_broadcast {
2780                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2781                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2782                         assert_eq!(node_txn.len(), 3);
2783                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2784                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2785                         check_spends!(node_txn[1], $commitment_tx);
2786                         check_spends!(node_txn[2], $commitment_tx);
2787                         assert_ne!(node_txn[1].lock_time.0, 0);
2788                         assert_ne!(node_txn[2].lock_time.0, 0);
2789                         if $htlc_offered {
2790                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2791                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2792                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2793                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2794                         } else {
2795                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2796                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2797                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2798                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2799                         }
2800                         check_spends!(node_txn[0], $chan_tx);
2801                         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2802                         node_txn.clear();
2803                 } }
2804         }
2805         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2806         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2807         // timeout-claim of the output that nodes[2] just claimed via success.
2808         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2809
2810         // Broadcast legit commitment tx from A on B's chain
2811         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2812         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2813         check_spends!(node_a_commitment_tx[0], chan_1.3);
2814         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2815         check_closed_broadcast!(nodes[1], true);
2816         check_added_monitors!(nodes[1], 1);
2817         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2818         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2819         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)
2820         let commitment_spend =
2821                 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2822                         if node_txn.len() == 6 {
2823                                 // In some block `ConnectionStyle`s we may avoid broadcasting the double-spending
2824                                 // transactions spending the HTLC outputs of C's commitment transaction. Otherwise,
2825                                 // check that the extra broadcasts (double-)spend those here.
2826                                 check_spends!(node_txn[1], commitment_tx[0]);
2827                                 check_spends!(node_txn[2], commitment_tx[0]);
2828                                 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2829                         }
2830                         &node_txn[0]
2831                 } else {
2832                         check_spends!(node_txn[0], commitment_tx[0]);
2833                         check_spends!(node_txn[1], commitment_tx[0]);
2834                         assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2835                         &node_txn[2]
2836                 };
2837
2838         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2839         assert_eq!(commitment_spend.input.len(), 2);
2840         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2841         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2842         assert_eq!(commitment_spend.lock_time.0, 0);
2843         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2844         let funding_spend_offset = if node_txn.len() == 6 { 3 } else { 1 };
2845         check_spends!(node_txn[funding_spend_offset], chan_1.3);
2846         assert_eq!(node_txn[funding_spend_offset].input[0].witness.clone().last().unwrap().len(), 71);
2847         check_spends!(node_txn[funding_spend_offset + 1], node_txn[funding_spend_offset]);
2848         check_spends!(node_txn[funding_spend_offset + 2], node_txn[funding_spend_offset]);
2849         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2850         // we already checked the same situation with A.
2851
2852         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2853         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2854         connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2855         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2856         check_closed_broadcast!(nodes[0], true);
2857         check_added_monitors!(nodes[0], 1);
2858         let events = nodes[0].node.get_and_clear_pending_events();
2859         assert_eq!(events.len(), 5);
2860         let mut first_claimed = false;
2861         for event in events {
2862                 match event {
2863                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2864                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2865                                         assert!(!first_claimed);
2866                                         first_claimed = true;
2867                                 } else {
2868                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2869                                         assert_eq!(payment_hash, payment_hash_2);
2870                                 }
2871                         },
2872                         Event::PaymentPathSuccessful { .. } => {},
2873                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2874                         _ => panic!("Unexpected event"),
2875                 }
2876         }
2877         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2878 }
2879
2880 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2881         // Test that in case of a unilateral close onchain, we detect the state of output and
2882         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2883         // broadcasting the right event to other nodes in payment path.
2884         // A ------------------> B ----------------------> C (timeout)
2885         //    B's commitment tx                 C's commitment tx
2886         //            \                                  \
2887         //         B's HTLC timeout tx               B's timeout tx
2888
2889         let chanmon_cfgs = create_chanmon_cfgs(3);
2890         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2891         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2892         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2893         *nodes[0].connect_style.borrow_mut() = connect_style;
2894         *nodes[1].connect_style.borrow_mut() = connect_style;
2895         *nodes[2].connect_style.borrow_mut() = connect_style;
2896
2897         // Create some intial channels
2898         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2899         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2900
2901         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2902         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2903         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2904
2905         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2906
2907         // Broadcast legit commitment tx from C on B's chain
2908         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2909         check_spends!(commitment_tx[0], chan_2.3);
2910         nodes[2].node.fail_htlc_backwards(&payment_hash);
2911         check_added_monitors!(nodes[2], 0);
2912         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2913         check_added_monitors!(nodes[2], 1);
2914
2915         let events = nodes[2].node.get_and_clear_pending_msg_events();
2916         assert_eq!(events.len(), 1);
2917         match events[0] {
2918                 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, .. } } => {
2919                         assert!(update_add_htlcs.is_empty());
2920                         assert!(!update_fail_htlcs.is_empty());
2921                         assert!(update_fulfill_htlcs.is_empty());
2922                         assert!(update_fail_malformed_htlcs.is_empty());
2923                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2924                 },
2925                 _ => panic!("Unexpected event"),
2926         };
2927         mine_transaction(&nodes[2], &commitment_tx[0]);
2928         check_closed_broadcast!(nodes[2], true);
2929         check_added_monitors!(nodes[2], 1);
2930         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2931         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2932         assert_eq!(node_txn.len(), 1);
2933         check_spends!(node_txn[0], chan_2.3);
2934         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2935
2936         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2937         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2938         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2939         mine_transaction(&nodes[1], &commitment_tx[0]);
2940         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2941         let timeout_tx;
2942         {
2943                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2944                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2945                 assert_eq!(node_txn[0], node_txn[3]);
2946                 assert_eq!(node_txn[1], node_txn[4]);
2947
2948                 check_spends!(node_txn[2], commitment_tx[0]);
2949                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2950
2951                 check_spends!(node_txn[0], chan_2.3);
2952                 check_spends!(node_txn[1], node_txn[0]);
2953                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2954                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2955
2956                 timeout_tx = node_txn[2].clone();
2957                 node_txn.clear();
2958         }
2959
2960         mine_transaction(&nodes[1], &timeout_tx);
2961         check_added_monitors!(nodes[1], 1);
2962         check_closed_broadcast!(nodes[1], true);
2963
2964         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2965
2966         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 }]);
2967         check_added_monitors!(nodes[1], 1);
2968         let events = nodes[1].node.get_and_clear_pending_msg_events();
2969         assert_eq!(events.len(), 1);
2970         match events[0] {
2971                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
2972                         assert!(update_add_htlcs.is_empty());
2973                         assert!(!update_fail_htlcs.is_empty());
2974                         assert!(update_fulfill_htlcs.is_empty());
2975                         assert!(update_fail_malformed_htlcs.is_empty());
2976                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2977                 },
2978                 _ => panic!("Unexpected event"),
2979         };
2980
2981         // Broadcast legit commitment tx from B on A's chain
2982         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2983         check_spends!(commitment_tx[0], chan_1.3);
2984
2985         mine_transaction(&nodes[0], &commitment_tx[0]);
2986         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2987
2988         check_closed_broadcast!(nodes[0], true);
2989         check_added_monitors!(nodes[0], 1);
2990         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2991         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
2992         assert_eq!(node_txn.len(), 2);
2993         check_spends!(node_txn[0], chan_1.3);
2994         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2995         check_spends!(node_txn[1], commitment_tx[0]);
2996         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2997 }
2998
2999 #[test]
3000 fn test_htlc_on_chain_timeout() {
3001         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3002         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3003         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3004 }
3005
3006 #[test]
3007 fn test_simple_commitment_revoked_fail_backward() {
3008         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3009         // and fail backward accordingly.
3010
3011         let chanmon_cfgs = create_chanmon_cfgs(3);
3012         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3013         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3014         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3015
3016         // Create some initial channels
3017         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3018         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3019
3020         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3021         // Get the will-be-revoked local txn from nodes[2]
3022         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3023         // Revoke the old state
3024         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3025
3026         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3027
3028         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3029         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3030         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3031         check_added_monitors!(nodes[1], 1);
3032         check_closed_broadcast!(nodes[1], true);
3033
3034         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 }]);
3035         check_added_monitors!(nodes[1], 1);
3036         let events = nodes[1].node.get_and_clear_pending_msg_events();
3037         assert_eq!(events.len(), 1);
3038         match events[0] {
3039                 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, .. } } => {
3040                         assert!(update_add_htlcs.is_empty());
3041                         assert_eq!(update_fail_htlcs.len(), 1);
3042                         assert!(update_fulfill_htlcs.is_empty());
3043                         assert!(update_fail_malformed_htlcs.is_empty());
3044                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3045
3046                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3047                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3048                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3049                 },
3050                 _ => panic!("Unexpected event"),
3051         }
3052 }
3053
3054 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3055         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3056         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3057         // commitment transaction anymore.
3058         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3059         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3060         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3061         // technically disallowed and we should probably handle it reasonably.
3062         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3063         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3064         // transactions:
3065         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3066         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3067         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3068         //   and once they revoke the previous commitment transaction (allowing us to send a new
3069         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3070         let chanmon_cfgs = create_chanmon_cfgs(3);
3071         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3072         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3073         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3074
3075         // Create some initial channels
3076         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3077         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3078
3079         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 });
3080         // Get the will-be-revoked local txn from nodes[2]
3081         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3082         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3083         // Revoke the old state
3084         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3085
3086         let value = if use_dust {
3087                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3088                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3089                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3090         } else { 3000000 };
3091
3092         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3093         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3094         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3095
3096         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3097         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3098         check_added_monitors!(nodes[2], 1);
3099         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3100         assert!(updates.update_add_htlcs.is_empty());
3101         assert!(updates.update_fulfill_htlcs.is_empty());
3102         assert!(updates.update_fail_malformed_htlcs.is_empty());
3103         assert_eq!(updates.update_fail_htlcs.len(), 1);
3104         assert!(updates.update_fee.is_none());
3105         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3106         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3107         // Drop the last RAA from 3 -> 2
3108
3109         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3110         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3111         check_added_monitors!(nodes[2], 1);
3112         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3113         assert!(updates.update_add_htlcs.is_empty());
3114         assert!(updates.update_fulfill_htlcs.is_empty());
3115         assert!(updates.update_fail_malformed_htlcs.is_empty());
3116         assert_eq!(updates.update_fail_htlcs.len(), 1);
3117         assert!(updates.update_fee.is_none());
3118         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3119         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3120         check_added_monitors!(nodes[1], 1);
3121         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3122         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3123         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3124         check_added_monitors!(nodes[2], 1);
3125
3126         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3127         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3128         check_added_monitors!(nodes[2], 1);
3129         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3130         assert!(updates.update_add_htlcs.is_empty());
3131         assert!(updates.update_fulfill_htlcs.is_empty());
3132         assert!(updates.update_fail_malformed_htlcs.is_empty());
3133         assert_eq!(updates.update_fail_htlcs.len(), 1);
3134         assert!(updates.update_fee.is_none());
3135         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3136         // At this point first_payment_hash has dropped out of the latest two commitment
3137         // transactions that nodes[1] is tracking...
3138         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3139         check_added_monitors!(nodes[1], 1);
3140         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3141         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3142         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3143         check_added_monitors!(nodes[2], 1);
3144
3145         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3146         // on nodes[2]'s RAA.
3147         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3148         nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3149         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3150         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3151         check_added_monitors!(nodes[1], 0);
3152
3153         if deliver_bs_raa {
3154                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3155                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3156                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3157                 check_added_monitors!(nodes[1], 1);
3158                 let events = nodes[1].node.get_and_clear_pending_events();
3159                 assert_eq!(events.len(), 2);
3160                 match events[0] {
3161                         Event::PendingHTLCsForwardable { .. } => { },
3162                         _ => panic!("Unexpected event"),
3163                 };
3164                 match events[1] {
3165                         Event::HTLCHandlingFailed { .. } => { },
3166                         _ => panic!("Unexpected event"),
3167                 }
3168                 // Deliberately don't process the pending fail-back so they all fail back at once after
3169                 // block connection just like the !deliver_bs_raa case
3170         }
3171
3172         let mut failed_htlcs = HashSet::new();
3173         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3174
3175         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3176         check_added_monitors!(nodes[1], 1);
3177         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3178
3179         let events = nodes[1].node.get_and_clear_pending_events();
3180         assert_eq!(events.len(), if deliver_bs_raa { 2 + nodes.len() - 1 } else { 3 + nodes.len() });
3181         match events[0] {
3182                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3183                 _ => panic!("Unexepected event"),
3184         }
3185         match events[1] {
3186                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3187                         assert_eq!(*payment_hash, fourth_payment_hash);
3188                 },
3189                 _ => panic!("Unexpected event"),
3190         }
3191         if !deliver_bs_raa {
3192                 match events[2] {
3193                         Event::PendingHTLCsForwardable { .. } => { },
3194                         _ => panic!("Unexpected event"),
3195                 };
3196                 nodes[1].node.abandon_payment(PaymentId(fourth_payment_hash.0));
3197                 let payment_failed_events = nodes[1].node.get_and_clear_pending_events();
3198                 assert_eq!(payment_failed_events.len(), 1);
3199                 match payment_failed_events[0] {
3200                         Event::PaymentFailed { ref payment_hash, .. } => {
3201                                 assert_eq!(*payment_hash, fourth_payment_hash);
3202                         },
3203                         _ => panic!("Unexpected event"),
3204                 }
3205         }
3206         nodes[1].node.process_pending_htlc_forwards();
3207         check_added_monitors!(nodes[1], 1);
3208
3209         let events = nodes[1].node.get_and_clear_pending_msg_events();
3210         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3211         match events[if deliver_bs_raa { 1 } else { 0 }] {
3212                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3213                 _ => panic!("Unexpected event"),
3214         }
3215         match events[if deliver_bs_raa { 2 } else { 1 }] {
3216                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3217                         assert_eq!(channel_id, chan_2.2);
3218                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3219                 },
3220                 _ => panic!("Unexpected event"),
3221         }
3222         if deliver_bs_raa {
3223                 match events[0] {
3224                         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, .. } } => {
3225                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3226                                 assert_eq!(update_add_htlcs.len(), 1);
3227                                 assert!(update_fulfill_htlcs.is_empty());
3228                                 assert!(update_fail_htlcs.is_empty());
3229                                 assert!(update_fail_malformed_htlcs.is_empty());
3230                         },
3231                         _ => panic!("Unexpected event"),
3232                 }
3233         }
3234         match events[if deliver_bs_raa { 3 } else { 2 }] {
3235                 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, .. } } => {
3236                         assert!(update_add_htlcs.is_empty());
3237                         assert_eq!(update_fail_htlcs.len(), 3);
3238                         assert!(update_fulfill_htlcs.is_empty());
3239                         assert!(update_fail_malformed_htlcs.is_empty());
3240                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3241
3242                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3243                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3244                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3245
3246                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3247
3248                         let events = nodes[0].node.get_and_clear_pending_events();
3249                         assert_eq!(events.len(), 3);
3250                         match events[0] {
3251                                 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3252                                         assert!(failed_htlcs.insert(payment_hash.0));
3253                                         // If we delivered B's RAA we got an unknown preimage error, not something
3254                                         // that we should update our routing table for.
3255                                         if !deliver_bs_raa {
3256                                                 assert!(network_update.is_some());
3257                                         }
3258                                 },
3259                                 _ => panic!("Unexpected event"),
3260                         }
3261                         match events[1] {
3262                                 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3263                                         assert!(failed_htlcs.insert(payment_hash.0));
3264                                         assert!(network_update.is_some());
3265                                 },
3266                                 _ => panic!("Unexpected event"),
3267                         }
3268                         match events[2] {
3269                                 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3270                                         assert!(failed_htlcs.insert(payment_hash.0));
3271                                         assert!(network_update.is_some());
3272                                 },
3273                                 _ => panic!("Unexpected event"),
3274                         }
3275                 },
3276                 _ => panic!("Unexpected event"),
3277         }
3278
3279         assert!(failed_htlcs.contains(&first_payment_hash.0));
3280         assert!(failed_htlcs.contains(&second_payment_hash.0));
3281         assert!(failed_htlcs.contains(&third_payment_hash.0));
3282 }
3283
3284 #[test]
3285 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3286         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3287         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3288         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3289         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3290 }
3291
3292 #[test]
3293 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3294         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3295         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3296         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3297         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3298 }
3299
3300 #[test]
3301 fn fail_backward_pending_htlc_upon_channel_failure() {
3302         let chanmon_cfgs = create_chanmon_cfgs(2);
3303         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3304         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3305         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3306         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());
3307
3308         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3309         {
3310                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3311                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
3312                 check_added_monitors!(nodes[0], 1);
3313
3314                 let payment_event = {
3315                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3316                         assert_eq!(events.len(), 1);
3317                         SendEvent::from_event(events.remove(0))
3318                 };
3319                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3320                 assert_eq!(payment_event.msgs.len(), 1);
3321         }
3322
3323         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3324         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3325         {
3326                 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3327                 check_added_monitors!(nodes[0], 0);
3328
3329                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3330         }
3331
3332         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3333         {
3334                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3335
3336                 let secp_ctx = Secp256k1::new();
3337                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3338                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3339                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3340                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3341                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3342
3343                 // Send a 0-msat update_add_htlc to fail the channel.
3344                 let update_add_htlc = msgs::UpdateAddHTLC {
3345                         channel_id: chan.2,
3346                         htlc_id: 0,
3347                         amount_msat: 0,
3348                         payment_hash,
3349                         cltv_expiry,
3350                         onion_routing_packet,
3351                 };
3352                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3353         }
3354         let events = nodes[0].node.get_and_clear_pending_events();
3355         assert_eq!(events.len(), 2);
3356         // Check that Alice fails backward the pending HTLC from the second payment.
3357         match events[0] {
3358                 Event::PaymentPathFailed { payment_hash, .. } => {
3359                         assert_eq!(payment_hash, failed_payment_hash);
3360                 },
3361                 _ => panic!("Unexpected event"),
3362         }
3363         match events[1] {
3364                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3365                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3366                 },
3367                 _ => panic!("Unexpected event {:?}", events[1]),
3368         }
3369         check_closed_broadcast!(nodes[0], true);
3370         check_added_monitors!(nodes[0], 1);
3371 }
3372
3373 #[test]
3374 fn test_htlc_ignore_latest_remote_commitment() {
3375         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3376         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3377         let chanmon_cfgs = create_chanmon_cfgs(2);
3378         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3379         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3380         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3381         if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3382                 // We rely on the ability to connect a block redundantly, which isn't allowed via
3383                 // `chain::Listen`, so we never run the test if we randomly get assigned that
3384                 // connect_style.
3385                 return;
3386         }
3387         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3388
3389         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3390         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3391         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3392         check_closed_broadcast!(nodes[0], true);
3393         check_added_monitors!(nodes[0], 1);
3394         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3395
3396         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3397         assert_eq!(node_txn.len(), 3);
3398         assert_eq!(node_txn[0], node_txn[1]);
3399
3400         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
3401         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3402         check_closed_broadcast!(nodes[1], true);
3403         check_added_monitors!(nodes[1], 1);
3404         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3405
3406         // Duplicate the connect_block call since this may happen due to other listeners
3407         // registering new transactions
3408         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3409 }
3410
3411 #[test]
3412 fn test_force_close_fail_back() {
3413         // Check which HTLCs are failed-backwards on channel force-closure
3414         let chanmon_cfgs = create_chanmon_cfgs(3);
3415         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3416         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3417         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3418         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3419         create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3420
3421         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3422
3423         let mut payment_event = {
3424                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3425                 check_added_monitors!(nodes[0], 1);
3426
3427                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3428                 assert_eq!(events.len(), 1);
3429                 SendEvent::from_event(events.remove(0))
3430         };
3431
3432         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3433         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3434
3435         expect_pending_htlcs_forwardable!(nodes[1]);
3436
3437         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3438         assert_eq!(events_2.len(), 1);
3439         payment_event = SendEvent::from_event(events_2.remove(0));
3440         assert_eq!(payment_event.msgs.len(), 1);
3441
3442         check_added_monitors!(nodes[1], 1);
3443         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3444         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3445         check_added_monitors!(nodes[2], 1);
3446         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3447
3448         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3449         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3450         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3451
3452         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3453         check_closed_broadcast!(nodes[2], true);
3454         check_added_monitors!(nodes[2], 1);
3455         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3456         let tx = {
3457                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3458                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3459                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3460                 // back to nodes[1] upon timeout otherwise.
3461                 assert_eq!(node_txn.len(), 1);
3462                 node_txn.remove(0)
3463         };
3464
3465         mine_transaction(&nodes[1], &tx);
3466
3467         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3468         check_closed_broadcast!(nodes[1], true);
3469         check_added_monitors!(nodes[1], 1);
3470         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3471
3472         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3473         {
3474                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3475                         .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);
3476         }
3477         mine_transaction(&nodes[2], &tx);
3478         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3479         assert_eq!(node_txn.len(), 1);
3480         assert_eq!(node_txn[0].input.len(), 1);
3481         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3482         assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3483         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3484
3485         check_spends!(node_txn[0], tx);
3486 }
3487
3488 #[test]
3489 fn test_dup_events_on_peer_disconnect() {
3490         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3491         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3492         // as we used to generate the event immediately upon receipt of the payment preimage in the
3493         // update_fulfill_htlc message.
3494
3495         let chanmon_cfgs = create_chanmon_cfgs(2);
3496         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3497         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3498         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3499         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3500
3501         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3502
3503         nodes[1].node.claim_funds(payment_preimage);
3504         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3505         check_added_monitors!(nodes[1], 1);
3506         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3507         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3508         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3509
3510         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3511         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3512
3513         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3514         expect_payment_path_successful!(nodes[0]);
3515 }
3516
3517 #[test]
3518 fn test_peer_disconnected_before_funding_broadcasted() {
3519         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3520         // before the funding transaction has been broadcasted.
3521         let chanmon_cfgs = create_chanmon_cfgs(2);
3522         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3523         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3524         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3525
3526         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3527         // broadcasted, even though it's created by `nodes[0]`.
3528         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();
3529         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3530         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
3531         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3532         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
3533
3534         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3535         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3536
3537         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3538
3539         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3540         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3541
3542         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3543         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3544         // broadcasted.
3545         {
3546                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3547         }
3548
3549         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3550         // disconnected before the funding transaction was broadcasted.
3551         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3552         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3553
3554         check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3555         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3556 }
3557
3558 #[test]
3559 fn test_simple_peer_disconnect() {
3560         // Test that we can reconnect when there are no lost messages
3561         let chanmon_cfgs = create_chanmon_cfgs(3);
3562         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3563         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3564         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3565         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3566         create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3567
3568         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3569         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3570         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3571
3572         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3573         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3574         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3575         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3576
3577         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3578         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3579         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3580
3581         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3582         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3583         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3584         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3585
3586         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3587         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3588
3589         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3590         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3591
3592         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3593         {
3594                 let events = nodes[0].node.get_and_clear_pending_events();
3595                 assert_eq!(events.len(), 3);
3596                 match events[0] {
3597                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3598                                 assert_eq!(payment_preimage, payment_preimage_3);
3599                                 assert_eq!(payment_hash, payment_hash_3);
3600                         },
3601                         _ => panic!("Unexpected event"),
3602                 }
3603                 match events[1] {
3604                         Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3605                                 assert_eq!(payment_hash, payment_hash_5);
3606                                 assert!(payment_failed_permanently);
3607                         },
3608                         _ => panic!("Unexpected event"),
3609                 }
3610                 match events[2] {
3611                         Event::PaymentPathSuccessful { .. } => {},
3612                         _ => panic!("Unexpected event"),
3613                 }
3614         }
3615
3616         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3617         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3618 }
3619
3620 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3621         // Test that we can reconnect when in-flight HTLC updates get dropped
3622         let chanmon_cfgs = create_chanmon_cfgs(2);
3623         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3624         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3625         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3626
3627         let mut as_channel_ready = None;
3628         if messages_delivered == 0 {
3629                 let (channel_ready, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3630                 as_channel_ready = Some(channel_ready);
3631                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3632                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3633                 // it before the channel_reestablish message.
3634         } else {
3635                 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3636         }
3637
3638         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3639
3640         let payment_event = {
3641                 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3642                 check_added_monitors!(nodes[0], 1);
3643
3644                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3645                 assert_eq!(events.len(), 1);
3646                 SendEvent::from_event(events.remove(0))
3647         };
3648         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3649
3650         if messages_delivered < 2 {
3651                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3652         } else {
3653                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3654                 if messages_delivered >= 3 {
3655                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3656                         check_added_monitors!(nodes[1], 1);
3657                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3658
3659                         if messages_delivered >= 4 {
3660                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3661                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3662                                 check_added_monitors!(nodes[0], 1);
3663
3664                                 if messages_delivered >= 5 {
3665                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3666                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3667                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3668                                         check_added_monitors!(nodes[0], 1);
3669
3670                                         if messages_delivered >= 6 {
3671                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3672                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3673                                                 check_added_monitors!(nodes[1], 1);
3674                                         }
3675                                 }
3676                         }
3677                 }
3678         }
3679
3680         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3681         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3682         if messages_delivered < 3 {
3683                 if simulate_broken_lnd {
3684                         // lnd has a long-standing bug where they send a channel_ready prior to a
3685                         // channel_reestablish if you reconnect prior to channel_ready time.
3686                         //
3687                         // Here we simulate that behavior, delivering a channel_ready immediately on
3688                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3689                         // in `reconnect_nodes` but we currently don't fail based on that.
3690                         //
3691                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3692                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3693                 }
3694                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3695                 // received on either side, both sides will need to resend them.
3696                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3697         } else if messages_delivered == 3 {
3698                 // nodes[0] still wants its RAA + commitment_signed
3699                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3700         } else if messages_delivered == 4 {
3701                 // nodes[0] still wants its commitment_signed
3702                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3703         } else if messages_delivered == 5 {
3704                 // nodes[1] still wants its final RAA
3705                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3706         } else if messages_delivered == 6 {
3707                 // Everything was delivered...
3708                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3709         }
3710
3711         let events_1 = nodes[1].node.get_and_clear_pending_events();
3712         if messages_delivered == 0 {
3713                 assert_eq!(events_1.len(), 2);
3714                 match events_1[0] {
3715                         Event::ChannelReady { .. } => { },
3716                         _ => panic!("Unexpected event"),
3717                 };
3718                 match events_1[1] {
3719                         Event::PendingHTLCsForwardable { .. } => { },
3720                         _ => panic!("Unexpected event"),
3721                 };
3722         } else {
3723                 assert_eq!(events_1.len(), 1);
3724                 match events_1[0] {
3725                         Event::PendingHTLCsForwardable { .. } => { },
3726                         _ => panic!("Unexpected event"),
3727                 };
3728         }
3729
3730         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3731         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3732         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3733
3734         nodes[1].node.process_pending_htlc_forwards();
3735
3736         let events_2 = nodes[1].node.get_and_clear_pending_events();
3737         assert_eq!(events_2.len(), 1);
3738         match events_2[0] {
3739                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat, receiver_node_id } => {
3740                         assert_eq!(payment_hash_1, *payment_hash);
3741                         assert_eq!(amount_msat, 1_000_000);
3742                         assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3743                         match &purpose {
3744                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3745                                         assert!(payment_preimage.is_none());
3746                                         assert_eq!(payment_secret_1, *payment_secret);
3747                                 },
3748                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3749                         }
3750                 },
3751                 _ => panic!("Unexpected event"),
3752         }
3753
3754         nodes[1].node.claim_funds(payment_preimage_1);
3755         check_added_monitors!(nodes[1], 1);
3756         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3757
3758         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3759         assert_eq!(events_3.len(), 1);
3760         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3761                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3762                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3763                         assert!(updates.update_add_htlcs.is_empty());
3764                         assert!(updates.update_fail_htlcs.is_empty());
3765                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3766                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3767                         assert!(updates.update_fee.is_none());
3768                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3769                 },
3770                 _ => panic!("Unexpected event"),
3771         };
3772
3773         if messages_delivered >= 1 {
3774                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3775
3776                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3777                 assert_eq!(events_4.len(), 1);
3778                 match events_4[0] {
3779                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3780                                 assert_eq!(payment_preimage_1, *payment_preimage);
3781                                 assert_eq!(payment_hash_1, *payment_hash);
3782                         },
3783                         _ => panic!("Unexpected event"),
3784                 }
3785
3786                 if messages_delivered >= 2 {
3787                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3788                         check_added_monitors!(nodes[0], 1);
3789                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3790
3791                         if messages_delivered >= 3 {
3792                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3793                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3794                                 check_added_monitors!(nodes[1], 1);
3795
3796                                 if messages_delivered >= 4 {
3797                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3798                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3799                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3800                                         check_added_monitors!(nodes[1], 1);
3801
3802                                         if messages_delivered >= 5 {
3803                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3804                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3805                                                 check_added_monitors!(nodes[0], 1);
3806                                         }
3807                                 }
3808                         }
3809                 }
3810         }
3811
3812         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3813         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3814         if messages_delivered < 2 {
3815                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3816                 if messages_delivered < 1 {
3817                         expect_payment_sent!(nodes[0], payment_preimage_1);
3818                 } else {
3819                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3820                 }
3821         } else if messages_delivered == 2 {
3822                 // nodes[0] still wants its RAA + commitment_signed
3823                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3824         } else if messages_delivered == 3 {
3825                 // nodes[0] still wants its commitment_signed
3826                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3827         } else if messages_delivered == 4 {
3828                 // nodes[1] still wants its final RAA
3829                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3830         } else if messages_delivered == 5 {
3831                 // Everything was delivered...
3832                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3833         }
3834
3835         if messages_delivered == 1 || messages_delivered == 2 {
3836                 expect_payment_path_successful!(nodes[0]);
3837         }
3838
3839         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3840         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3841         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3842
3843         if messages_delivered > 2 {
3844                 expect_payment_path_successful!(nodes[0]);
3845         }
3846
3847         // Channel should still work fine...
3848         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3849         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3850         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3851 }
3852
3853 #[test]
3854 fn test_drop_messages_peer_disconnect_a() {
3855         do_test_drop_messages_peer_disconnect(0, true);
3856         do_test_drop_messages_peer_disconnect(0, false);
3857         do_test_drop_messages_peer_disconnect(1, false);
3858         do_test_drop_messages_peer_disconnect(2, false);
3859 }
3860
3861 #[test]
3862 fn test_drop_messages_peer_disconnect_b() {
3863         do_test_drop_messages_peer_disconnect(3, false);
3864         do_test_drop_messages_peer_disconnect(4, false);
3865         do_test_drop_messages_peer_disconnect(5, false);
3866         do_test_drop_messages_peer_disconnect(6, false);
3867 }
3868
3869 #[test]
3870 fn test_channel_ready_without_best_block_updated() {
3871         // Previously, if we were offline when a funding transaction was locked in, and then we came
3872         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3873         // generate a channel_ready until a later best_block_updated. This tests that we generate the
3874         // channel_ready immediately instead.
3875         let chanmon_cfgs = create_chanmon_cfgs(2);
3876         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3877         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3878         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3879         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3880
3881         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());
3882
3883         let conf_height = nodes[0].best_block_info().1 + 1;
3884         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3885         let block_txn = [funding_tx];
3886         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3887         let conf_block_header = nodes[0].get_block_header(conf_height);
3888         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3889
3890         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
3891         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
3892         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3893 }
3894
3895 #[test]
3896 fn test_drop_messages_peer_disconnect_dual_htlc() {
3897         // Test that we can handle reconnecting when both sides of a channel have pending
3898         // commitment_updates when we disconnect.
3899         let chanmon_cfgs = create_chanmon_cfgs(2);
3900         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3901         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3902         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3903         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
3904
3905         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3906
3907         // Now try to send a second payment which will fail to send
3908         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3909         nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
3910         check_added_monitors!(nodes[0], 1);
3911
3912         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3913         assert_eq!(events_1.len(), 1);
3914         match events_1[0] {
3915                 MessageSendEvent::UpdateHTLCs { .. } => {},
3916                 _ => panic!("Unexpected event"),
3917         }
3918
3919         nodes[1].node.claim_funds(payment_preimage_1);
3920         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3921         check_added_monitors!(nodes[1], 1);
3922
3923         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3924         assert_eq!(events_2.len(), 1);
3925         match events_2[0] {
3926                 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 } } => {
3927                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3928                         assert!(update_add_htlcs.is_empty());
3929                         assert_eq!(update_fulfill_htlcs.len(), 1);
3930                         assert!(update_fail_htlcs.is_empty());
3931                         assert!(update_fail_malformed_htlcs.is_empty());
3932                         assert!(update_fee.is_none());
3933
3934                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3935                         let events_3 = nodes[0].node.get_and_clear_pending_events();
3936                         assert_eq!(events_3.len(), 1);
3937                         match events_3[0] {
3938                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3939                                         assert_eq!(*payment_preimage, payment_preimage_1);
3940                                         assert_eq!(*payment_hash, payment_hash_1);
3941                                 },
3942                                 _ => panic!("Unexpected event"),
3943                         }
3944
3945                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3946                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3947                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3948                         check_added_monitors!(nodes[0], 1);
3949                 },
3950                 _ => panic!("Unexpected event"),
3951         }
3952
3953         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3954         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3955
3956         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
3957         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3958         assert_eq!(reestablish_1.len(), 1);
3959         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
3960         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3961         assert_eq!(reestablish_2.len(), 1);
3962
3963         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3964         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3965         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3966         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3967
3968         assert!(as_resp.0.is_none());
3969         assert!(bs_resp.0.is_none());
3970
3971         assert!(bs_resp.1.is_none());
3972         assert!(bs_resp.2.is_none());
3973
3974         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3975
3976         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3977         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3978         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3979         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3980         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3981         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3982         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3983         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3984         // No commitment_signed so get_event_msg's assert(len == 1) passes
3985         check_added_monitors!(nodes[1], 1);
3986
3987         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3988         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3989         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3990         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3991         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3992         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3993         assert!(bs_second_commitment_signed.update_fee.is_none());
3994         check_added_monitors!(nodes[1], 1);
3995
3996         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3997         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3998         assert!(as_commitment_signed.update_add_htlcs.is_empty());
3999         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4000         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4001         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4002         assert!(as_commitment_signed.update_fee.is_none());
4003         check_added_monitors!(nodes[0], 1);
4004
4005         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4006         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4007         // No commitment_signed so get_event_msg's assert(len == 1) passes
4008         check_added_monitors!(nodes[0], 1);
4009
4010         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4011         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4012         // No commitment_signed so get_event_msg's assert(len == 1) passes
4013         check_added_monitors!(nodes[1], 1);
4014
4015         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4016         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4017         check_added_monitors!(nodes[1], 1);
4018
4019         expect_pending_htlcs_forwardable!(nodes[1]);
4020
4021         let events_5 = nodes[1].node.get_and_clear_pending_events();
4022         assert_eq!(events_5.len(), 1);
4023         match events_5[0] {
4024                 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4025                         assert_eq!(payment_hash_2, *payment_hash);
4026                         match &purpose {
4027                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4028                                         assert!(payment_preimage.is_none());
4029                                         assert_eq!(payment_secret_2, *payment_secret);
4030                                 },
4031                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4032                         }
4033                 },
4034                 _ => panic!("Unexpected event"),
4035         }
4036
4037         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4038         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4039         check_added_monitors!(nodes[0], 1);
4040
4041         expect_payment_path_successful!(nodes[0]);
4042         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4043 }
4044
4045 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4046         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4047         // to avoid our counterparty failing the channel.
4048         let chanmon_cfgs = create_chanmon_cfgs(2);
4049         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4050         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4051         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4052
4053         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4054
4055         let our_payment_hash = if send_partial_mpp {
4056                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4057                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4058                 // indicates there are more HTLCs coming.
4059                 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.
4060                 let payment_id = PaymentId([42; 32]);
4061                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(payment_secret), payment_id, &route).unwrap();
4062                 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();
4063                 check_added_monitors!(nodes[0], 1);
4064                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4065                 assert_eq!(events.len(), 1);
4066                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4067                 // hop should *not* yet generate any PaymentReceived event(s).
4068                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4069                 our_payment_hash
4070         } else {
4071                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4072         };
4073
4074         let mut block = Block {
4075                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
4076                 txdata: vec![],
4077         };
4078         connect_block(&nodes[0], &block);
4079         connect_block(&nodes[1], &block);
4080         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4081         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4082                 block.header.prev_blockhash = block.block_hash();
4083                 connect_block(&nodes[0], &block);
4084                 connect_block(&nodes[1], &block);
4085         }
4086
4087         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4088
4089         check_added_monitors!(nodes[1], 1);
4090         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4091         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4092         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4093         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4094         assert!(htlc_timeout_updates.update_fee.is_none());
4095
4096         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4097         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4098         // 100_000 msat as u64, followed by the height at which we failed back above
4099         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4100         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4101         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4102 }
4103
4104 #[test]
4105 fn test_htlc_timeout() {
4106         do_test_htlc_timeout(true);
4107         do_test_htlc_timeout(false);
4108 }
4109
4110 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4111         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4112         let chanmon_cfgs = create_chanmon_cfgs(3);
4113         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4114         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4115         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4116         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4117         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4118
4119         // Make sure all nodes are at the same starting height
4120         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4121         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4122         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4123
4124         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4125         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4126         {
4127                 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4128         }
4129         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4130         check_added_monitors!(nodes[1], 1);
4131
4132         // Now attempt to route a second payment, which should be placed in the holding cell
4133         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4134         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4135         sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4136         if forwarded_htlc {
4137                 check_added_monitors!(nodes[0], 1);
4138                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4139                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4140                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4141                 expect_pending_htlcs_forwardable!(nodes[1]);
4142         }
4143         check_added_monitors!(nodes[1], 0);
4144
4145         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4146         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4147         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4148         connect_blocks(&nodes[1], 1);
4149
4150         if forwarded_htlc {
4151                 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 }]);
4152                 check_added_monitors!(nodes[1], 1);
4153                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4154                 assert_eq!(fail_commit.len(), 1);
4155                 match fail_commit[0] {
4156                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4157                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4158                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4159                         },
4160                         _ => unreachable!(),
4161                 }
4162                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4163         } else {
4164                 expect_payment_failed!(nodes[1], second_payment_hash, false);
4165         }
4166 }
4167
4168 #[test]
4169 fn test_holding_cell_htlc_add_timeouts() {
4170         do_test_holding_cell_htlc_add_timeouts(false);
4171         do_test_holding_cell_htlc_add_timeouts(true);
4172 }
4173
4174 macro_rules! check_spendable_outputs {
4175         ($node: expr, $keysinterface: expr) => {
4176                 {
4177                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4178                         let mut txn = Vec::new();
4179                         let mut all_outputs = Vec::new();
4180                         let secp_ctx = Secp256k1::new();
4181                         for event in events.drain(..) {
4182                                 match event {
4183                                         Event::SpendableOutputs { mut outputs } => {
4184                                                 for outp in outputs.drain(..) {
4185                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4186                                                         all_outputs.push(outp);
4187                                                 }
4188                                         },
4189                                         _ => panic!("Unexpected event"),
4190                                 };
4191                         }
4192                         if all_outputs.len() > 1 {
4193                                 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) {
4194                                         txn.push(tx);
4195                                 }
4196                         }
4197                         txn
4198                 }
4199         }
4200 }
4201
4202 #[test]
4203 fn test_claim_sizeable_push_msat() {
4204         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4205         let chanmon_cfgs = create_chanmon_cfgs(2);
4206         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4207         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4208         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4209
4210         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());
4211         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4212         check_closed_broadcast!(nodes[1], true);
4213         check_added_monitors!(nodes[1], 1);
4214         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4215         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4216         assert_eq!(node_txn.len(), 1);
4217         check_spends!(node_txn[0], chan.3);
4218         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
4219
4220         mine_transaction(&nodes[1], &node_txn[0]);
4221         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4222
4223         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4224         assert_eq!(spend_txn.len(), 1);
4225         assert_eq!(spend_txn[0].input.len(), 1);
4226         check_spends!(spend_txn[0], node_txn[0]);
4227         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4228 }
4229
4230 #[test]
4231 fn test_claim_on_remote_sizeable_push_msat() {
4232         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4233         // to_remote output is encumbered by a P2WPKH
4234         let chanmon_cfgs = create_chanmon_cfgs(2);
4235         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4236         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4237         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4238
4239         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());
4240         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4241         check_closed_broadcast!(nodes[0], true);
4242         check_added_monitors!(nodes[0], 1);
4243         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4244
4245         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4246         assert_eq!(node_txn.len(), 1);
4247         check_spends!(node_txn[0], chan.3);
4248         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
4249
4250         mine_transaction(&nodes[1], &node_txn[0]);
4251         check_closed_broadcast!(nodes[1], true);
4252         check_added_monitors!(nodes[1], 1);
4253         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4254         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4255
4256         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4257         assert_eq!(spend_txn.len(), 1);
4258         check_spends!(spend_txn[0], node_txn[0]);
4259 }
4260
4261 #[test]
4262 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4263         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4264         // to_remote output is encumbered by a P2WPKH
4265
4266         let chanmon_cfgs = create_chanmon_cfgs(2);
4267         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4268         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4269         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4270
4271         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4272         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4273         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4274         assert_eq!(revoked_local_txn[0].input.len(), 1);
4275         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4276
4277         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4278         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4279         check_closed_broadcast!(nodes[1], true);
4280         check_added_monitors!(nodes[1], 1);
4281         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4282
4283         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4284         mine_transaction(&nodes[1], &node_txn[0]);
4285         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4286
4287         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4288         assert_eq!(spend_txn.len(), 3);
4289         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4290         check_spends!(spend_txn[1], node_txn[0]);
4291         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4292 }
4293
4294 #[test]
4295 fn test_static_spendable_outputs_preimage_tx() {
4296         let chanmon_cfgs = create_chanmon_cfgs(2);
4297         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4298         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4299         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4300
4301         // Create some initial channels
4302         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4303
4304         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4305
4306         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4307         assert_eq!(commitment_tx[0].input.len(), 1);
4308         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4309
4310         // Settle A's commitment tx on B's chain
4311         nodes[1].node.claim_funds(payment_preimage);
4312         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4313         check_added_monitors!(nodes[1], 1);
4314         mine_transaction(&nodes[1], &commitment_tx[0]);
4315         check_added_monitors!(nodes[1], 1);
4316         let events = nodes[1].node.get_and_clear_pending_msg_events();
4317         match events[0] {
4318                 MessageSendEvent::UpdateHTLCs { .. } => {},
4319                 _ => panic!("Unexpected event"),
4320         }
4321         match events[1] {
4322                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4323                 _ => panic!("Unexepected event"),
4324         }
4325
4326         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4327         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4328         assert_eq!(node_txn.len(), 3);
4329         check_spends!(node_txn[0], commitment_tx[0]);
4330         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4331         check_spends!(node_txn[1], chan_1.3);
4332         check_spends!(node_txn[2], node_txn[1]);
4333
4334         mine_transaction(&nodes[1], &node_txn[0]);
4335         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4336         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4337
4338         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4339         assert_eq!(spend_txn.len(), 1);
4340         check_spends!(spend_txn[0], node_txn[0]);
4341 }
4342
4343 #[test]
4344 fn test_static_spendable_outputs_timeout_tx() {
4345         let chanmon_cfgs = create_chanmon_cfgs(2);
4346         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4347         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4348         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4349
4350         // Create some initial channels
4351         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4352
4353         // Rebalance the network a bit by relaying one payment through all the channels ...
4354         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4355
4356         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4357
4358         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4359         assert_eq!(commitment_tx[0].input.len(), 1);
4360         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4361
4362         // Settle A's commitment tx on B' chain
4363         mine_transaction(&nodes[1], &commitment_tx[0]);
4364         check_added_monitors!(nodes[1], 1);
4365         let events = nodes[1].node.get_and_clear_pending_msg_events();
4366         match events[0] {
4367                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4368                 _ => panic!("Unexpected event"),
4369         }
4370         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4371
4372         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4373         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4374         assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4375         check_spends!(node_txn[0], chan_1.3.clone());
4376         check_spends!(node_txn[1],  commitment_tx[0].clone());
4377         assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4378
4379         mine_transaction(&nodes[1], &node_txn[1]);
4380         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4381         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4382         expect_payment_failed!(nodes[1], our_payment_hash, false);
4383
4384         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4385         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4386         check_spends!(spend_txn[0], commitment_tx[0]);
4387         check_spends!(spend_txn[1], node_txn[1]);
4388         check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4389 }
4390
4391 #[test]
4392 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4393         let chanmon_cfgs = create_chanmon_cfgs(2);
4394         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4395         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4396         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4397
4398         // Create some initial channels
4399         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4400
4401         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4402         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4403         assert_eq!(revoked_local_txn[0].input.len(), 1);
4404         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4405
4406         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4407
4408         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4409         check_closed_broadcast!(nodes[1], true);
4410         check_added_monitors!(nodes[1], 1);
4411         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4412
4413         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4414         assert_eq!(node_txn.len(), 2);
4415         assert_eq!(node_txn[0].input.len(), 2);
4416         check_spends!(node_txn[0], revoked_local_txn[0]);
4417
4418         mine_transaction(&nodes[1], &node_txn[0]);
4419         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4420
4421         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4422         assert_eq!(spend_txn.len(), 1);
4423         check_spends!(spend_txn[0], node_txn[0]);
4424 }
4425
4426 #[test]
4427 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4428         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4429         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4430         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4431         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4432         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4433
4434         // Create some initial channels
4435         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4436
4437         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4438         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4439         assert_eq!(revoked_local_txn[0].input.len(), 1);
4440         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4441
4442         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4443
4444         // A will generate HTLC-Timeout from revoked commitment tx
4445         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4446         check_closed_broadcast!(nodes[0], true);
4447         check_added_monitors!(nodes[0], 1);
4448         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4449         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4450
4451         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4452         assert_eq!(revoked_htlc_txn.len(), 2);
4453         check_spends!(revoked_htlc_txn[0], chan_1.3);
4454         assert_eq!(revoked_htlc_txn[1].input.len(), 1);
4455         assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4456         check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
4457         assert_ne!(revoked_htlc_txn[1].lock_time.0, 0); // HTLC-Timeout
4458
4459         // B will generate justice tx from A's revoked commitment/HTLC tx
4460         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4461         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
4462         check_closed_broadcast!(nodes[1], true);
4463         check_added_monitors!(nodes[1], 1);
4464         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4465
4466         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4467         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4468         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4469         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4470         // transactions next...
4471         assert_eq!(node_txn[0].input.len(), 3);
4472         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
4473
4474         assert_eq!(node_txn[1].input.len(), 2);
4475         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
4476         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
4477                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4478         } else {
4479                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
4480                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4481         }
4482
4483         assert_eq!(node_txn[2].input.len(), 1);
4484         check_spends!(node_txn[2], chan_1.3);
4485
4486         mine_transaction(&nodes[1], &node_txn[1]);
4487         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4488
4489         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4490         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4491         assert_eq!(spend_txn.len(), 1);
4492         assert_eq!(spend_txn[0].input.len(), 1);
4493         check_spends!(spend_txn[0], node_txn[1]);
4494 }
4495
4496 #[test]
4497 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4498         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4499         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4500         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4501         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4502         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4503
4504         // Create some initial channels
4505         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4506
4507         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4508         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4509         assert_eq!(revoked_local_txn[0].input.len(), 1);
4510         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4511
4512         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4513         assert_eq!(revoked_local_txn[0].output.len(), 2);
4514
4515         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4516
4517         // B will generate HTLC-Success from revoked commitment tx
4518         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4519         check_closed_broadcast!(nodes[1], true);
4520         check_added_monitors!(nodes[1], 1);
4521         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4522         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4523
4524         assert_eq!(revoked_htlc_txn.len(), 2);
4525         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4526         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4527         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4528
4529         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4530         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4531         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4532
4533         // A will generate justice tx from B's revoked commitment/HTLC tx
4534         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4535         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4536         check_closed_broadcast!(nodes[0], true);
4537         check_added_monitors!(nodes[0], 1);
4538         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4539
4540         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4541         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
4542
4543         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4544         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4545         // transactions next...
4546         assert_eq!(node_txn[0].input.len(), 2);
4547         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4548         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4549                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4550         } else {
4551                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4552                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4553         }
4554
4555         assert_eq!(node_txn[1].input.len(), 1);
4556         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4557
4558         check_spends!(node_txn[2], chan_1.3);
4559
4560         mine_transaction(&nodes[0], &node_txn[1]);
4561         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4562
4563         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4564         // didn't try to generate any new transactions.
4565
4566         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4567         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4568         assert_eq!(spend_txn.len(), 3);
4569         assert_eq!(spend_txn[0].input.len(), 1);
4570         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4571         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4572         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4573         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4574 }
4575
4576 #[test]
4577 fn test_onchain_to_onchain_claim() {
4578         // Test that in case of channel closure, we detect the state of output and claim HTLC
4579         // on downstream peer's remote commitment tx.
4580         // First, have C claim an HTLC against its own latest commitment transaction.
4581         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4582         // channel.
4583         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4584         // gets broadcast.
4585
4586         let chanmon_cfgs = create_chanmon_cfgs(3);
4587         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4588         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4589         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4590
4591         // Create some initial channels
4592         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4593         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4594
4595         // Ensure all nodes are at the same height
4596         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4597         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4598         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4599         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4600
4601         // Rebalance the network a bit by relaying one payment through all the channels ...
4602         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4603         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4604
4605         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4606         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4607         check_spends!(commitment_tx[0], chan_2.3);
4608         nodes[2].node.claim_funds(payment_preimage);
4609         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4610         check_added_monitors!(nodes[2], 1);
4611         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4612         assert!(updates.update_add_htlcs.is_empty());
4613         assert!(updates.update_fail_htlcs.is_empty());
4614         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4615         assert!(updates.update_fail_malformed_htlcs.is_empty());
4616
4617         mine_transaction(&nodes[2], &commitment_tx[0]);
4618         check_closed_broadcast!(nodes[2], true);
4619         check_added_monitors!(nodes[2], 1);
4620         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4621
4622         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
4623         assert_eq!(c_txn.len(), 3);
4624         assert_eq!(c_txn[0], c_txn[2]);
4625         assert_eq!(commitment_tx[0], c_txn[1]);
4626         check_spends!(c_txn[1], chan_2.3);
4627         check_spends!(c_txn[2], c_txn[1]);
4628         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
4629         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4630         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4631         assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4632
4633         // 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
4634         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
4635         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
4636         check_added_monitors!(nodes[1], 1);
4637         let events = nodes[1].node.get_and_clear_pending_events();
4638         assert_eq!(events.len(), 2);
4639         match events[0] {
4640                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4641                 _ => panic!("Unexpected event"),
4642         }
4643         match events[1] {
4644                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
4645                         assert_eq!(fee_earned_msat, Some(1000));
4646                         assert_eq!(prev_channel_id, Some(chan_1.2));
4647                         assert_eq!(claim_from_onchain_tx, true);
4648                         assert_eq!(next_channel_id, Some(chan_2.2));
4649                 },
4650                 _ => panic!("Unexpected event"),
4651         }
4652         {
4653                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4654                 // ChannelMonitor: claim tx
4655                 assert_eq!(b_txn.len(), 1);
4656                 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
4657                 b_txn.clear();
4658         }
4659         check_added_monitors!(nodes[1], 1);
4660         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4661         assert_eq!(msg_events.len(), 3);
4662         match msg_events[0] {
4663                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4664                 _ => panic!("Unexpected event"),
4665         }
4666         match msg_events[1] {
4667                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4668                 _ => panic!("Unexpected event"),
4669         }
4670         match msg_events[2] {
4671                 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, .. } } => {
4672                         assert!(update_add_htlcs.is_empty());
4673                         assert!(update_fail_htlcs.is_empty());
4674                         assert_eq!(update_fulfill_htlcs.len(), 1);
4675                         assert!(update_fail_malformed_htlcs.is_empty());
4676                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4677                 },
4678                 _ => panic!("Unexpected event"),
4679         };
4680         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4681         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4682         mine_transaction(&nodes[1], &commitment_tx[0]);
4683         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4684         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4685         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
4686         assert_eq!(b_txn.len(), 3);
4687         check_spends!(b_txn[1], chan_1.3);
4688         check_spends!(b_txn[2], b_txn[1]);
4689         check_spends!(b_txn[0], commitment_tx[0]);
4690         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4691         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4692         assert_eq!(b_txn[0].lock_time.0, 0); // Success tx
4693
4694         check_closed_broadcast!(nodes[1], true);
4695         check_added_monitors!(nodes[1], 1);
4696 }
4697
4698 #[test]
4699 fn test_duplicate_payment_hash_one_failure_one_success() {
4700         // Topology : A --> B --> C --> D
4701         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4702         // Note that because C will refuse to generate two payment secrets for the same payment hash,
4703         // we forward one of the payments onwards to D.
4704         let chanmon_cfgs = create_chanmon_cfgs(4);
4705         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4706         // When this test was written, the default base fee floated based on the HTLC count.
4707         // It is now fixed, so we simply set the fee to the expected value here.
4708         let mut config = test_default_channel_config();
4709         config.channel_config.forwarding_fee_base_msat = 196;
4710         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4711                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4712         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4713
4714         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4715         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4716         create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4717
4718         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4719         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4720         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4721         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4722         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4723
4724         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4725
4726         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
4727         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4728         // script push size limit so that the below script length checks match
4729         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4730         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
4731                 .with_features(channelmanager::provided_invoice_features());
4732         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 900000, TEST_FINAL_CLTV - 40);
4733         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
4734
4735         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4736         assert_eq!(commitment_txn[0].input.len(), 1);
4737         check_spends!(commitment_txn[0], chan_2.3);
4738
4739         mine_transaction(&nodes[1], &commitment_txn[0]);
4740         check_closed_broadcast!(nodes[1], true);
4741         check_added_monitors!(nodes[1], 1);
4742         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4743         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
4744
4745         let htlc_timeout_tx;
4746         { // Extract one of the two HTLC-Timeout transaction
4747                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4748                 // ChannelMonitor: timeout tx * 2-or-3, ChannelManager: local commitment tx
4749                 assert!(node_txn.len() == 4 || node_txn.len() == 3);
4750                 check_spends!(node_txn[0], chan_2.3);
4751
4752                 check_spends!(node_txn[1], commitment_txn[0]);
4753                 assert_eq!(node_txn[1].input.len(), 1);
4754
4755                 if node_txn.len() > 3 {
4756                         check_spends!(node_txn[2], commitment_txn[0]);
4757                         assert_eq!(node_txn[2].input.len(), 1);
4758                         assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
4759
4760                         check_spends!(node_txn[3], commitment_txn[0]);
4761                         assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
4762                 } else {
4763                         check_spends!(node_txn[2], commitment_txn[0]);
4764                         assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
4765                 }
4766
4767                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4768                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4769                 if node_txn.len() > 3 {
4770                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4771                 }
4772                 htlc_timeout_tx = node_txn[1].clone();
4773         }
4774
4775         nodes[2].node.claim_funds(our_payment_preimage);
4776         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4777
4778         mine_transaction(&nodes[2], &commitment_txn[0]);
4779         check_added_monitors!(nodes[2], 2);
4780         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4781         let events = nodes[2].node.get_and_clear_pending_msg_events();
4782         match events[0] {
4783                 MessageSendEvent::UpdateHTLCs { .. } => {},
4784                 _ => panic!("Unexpected event"),
4785         }
4786         match events[1] {
4787                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4788                 _ => panic!("Unexepected event"),
4789         }
4790         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4791         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)
4792         check_spends!(htlc_success_txn[0], commitment_txn[0]);
4793         check_spends!(htlc_success_txn[1], commitment_txn[0]);
4794         assert_eq!(htlc_success_txn[0].input.len(), 1);
4795         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4796         assert_eq!(htlc_success_txn[1].input.len(), 1);
4797         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4798         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4799         assert_eq!(htlc_success_txn[2], commitment_txn[0]);
4800         assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
4801         assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
4802         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4803
4804         mine_transaction(&nodes[1], &htlc_timeout_tx);
4805         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4806         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 }]);
4807         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4808         assert!(htlc_updates.update_add_htlcs.is_empty());
4809         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4810         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4811         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4812         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4813         check_added_monitors!(nodes[1], 1);
4814
4815         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4816         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4817         {
4818                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4819         }
4820         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
4821
4822         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4823         // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
4824         // and nodes[2] fee) is rounded down and then claimed in full.
4825         mine_transaction(&nodes[1], &htlc_success_txn[0]);
4826         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196*2), true, true);
4827         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4828         assert!(updates.update_add_htlcs.is_empty());
4829         assert!(updates.update_fail_htlcs.is_empty());
4830         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4831         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
4832         assert!(updates.update_fail_malformed_htlcs.is_empty());
4833         check_added_monitors!(nodes[1], 1);
4834
4835         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4836         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4837
4838         let events = nodes[0].node.get_and_clear_pending_events();
4839         match events[0] {
4840                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4841                         assert_eq!(*payment_preimage, our_payment_preimage);
4842                         assert_eq!(*payment_hash, duplicate_payment_hash);
4843                 }
4844                 _ => panic!("Unexpected event"),
4845         }
4846 }
4847
4848 #[test]
4849 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4850         let chanmon_cfgs = create_chanmon_cfgs(2);
4851         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4852         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4853         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4854
4855         // Create some initial channels
4856         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4857
4858         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
4859         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4860         assert_eq!(local_txn.len(), 1);
4861         assert_eq!(local_txn[0].input.len(), 1);
4862         check_spends!(local_txn[0], chan_1.3);
4863
4864         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4865         nodes[1].node.claim_funds(payment_preimage);
4866         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
4867         check_added_monitors!(nodes[1], 1);
4868
4869         mine_transaction(&nodes[1], &local_txn[0]);
4870         check_added_monitors!(nodes[1], 1);
4871         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4872         let events = nodes[1].node.get_and_clear_pending_msg_events();
4873         match events[0] {
4874                 MessageSendEvent::UpdateHTLCs { .. } => {},
4875                 _ => panic!("Unexpected event"),
4876         }
4877         match events[1] {
4878                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4879                 _ => panic!("Unexepected event"),
4880         }
4881         let node_tx = {
4882                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4883                 assert_eq!(node_txn.len(), 3);
4884                 assert_eq!(node_txn[0], node_txn[2]);
4885                 assert_eq!(node_txn[1], local_txn[0]);
4886                 assert_eq!(node_txn[0].input.len(), 1);
4887                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4888                 check_spends!(node_txn[0], local_txn[0]);
4889                 node_txn[0].clone()
4890         };
4891
4892         mine_transaction(&nodes[1], &node_tx);
4893         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4894
4895         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4896         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4897         assert_eq!(spend_txn.len(), 1);
4898         assert_eq!(spend_txn[0].input.len(), 1);
4899         check_spends!(spend_txn[0], node_tx);
4900         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4901 }
4902
4903 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4904         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4905         // unrevoked commitment transaction.
4906         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4907         // a remote RAA before they could be failed backwards (and combinations thereof).
4908         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4909         // use the same payment hashes.
4910         // Thus, we use a six-node network:
4911         //
4912         // A \         / E
4913         //    - C - D -
4914         // B /         \ F
4915         // And test where C fails back to A/B when D announces its latest commitment transaction
4916         let chanmon_cfgs = create_chanmon_cfgs(6);
4917         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4918         // When this test was written, the default base fee floated based on the HTLC count.
4919         // It is now fixed, so we simply set the fee to the expected value here.
4920         let mut config = test_default_channel_config();
4921         config.channel_config.forwarding_fee_base_msat = 196;
4922         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
4923                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4924         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4925
4926         let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4927         let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4928         let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4929         let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4930         let chan_3_5  = create_announced_chan_between_nodes(&nodes, 3, 5, channelmanager::provided_init_features(), channelmanager::provided_init_features());
4931
4932         // Rebalance and check output sanity...
4933         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
4934         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
4935         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
4936
4937         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
4938         // 0th HTLC:
4939         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
4940         // 1st HTLC:
4941         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
4942         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4943         // 2nd HTLC:
4944         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
4945         // 3rd HTLC:
4946         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
4947         // 4th HTLC:
4948         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4949         // 5th HTLC:
4950         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4951         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
4952         // 6th HTLC:
4953         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());
4954         // 7th HTLC:
4955         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());
4956
4957         // 8th HTLC:
4958         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4959         // 9th HTLC:
4960         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4961         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
4962
4963         // 10th HTLC:
4964         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
4965         // 11th HTLC:
4966         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
4967         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());
4968
4969         // Double-check that six of the new HTLC were added
4970         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
4971         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
4972         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
4973         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
4974
4975         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
4976         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
4977         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
4978         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
4979         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
4980         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
4981         check_added_monitors!(nodes[4], 0);
4982
4983         let failed_destinations = vec![
4984                 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
4985                 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
4986                 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
4987                 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
4988         ];
4989         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
4990         check_added_monitors!(nodes[4], 1);
4991
4992         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
4993         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
4994         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
4995         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
4996         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
4997         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
4998
4999         // Fail 3rd below-dust and 7th above-dust HTLCs
5000         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5001         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5002         check_added_monitors!(nodes[5], 0);
5003
5004         let failed_destinations_2 = vec![
5005                 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5006                 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5007         ];
5008         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5009         check_added_monitors!(nodes[5], 1);
5010
5011         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5012         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5013         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5014         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5015
5016         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5017
5018         // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5019         let failed_destinations_3 = vec![
5020                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5021                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5022                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5023                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5024                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5025                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5026         ];
5027         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5028         check_added_monitors!(nodes[3], 1);
5029         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5030         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5031         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5032         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5033         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5034         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5035         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5036         if deliver_last_raa {
5037                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5038         } else {
5039                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5040         }
5041
5042         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5043         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5044         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5045         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5046         //
5047         // We now broadcast the latest commitment transaction, which *should* result in failures for
5048         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5049         // the non-broadcast above-dust HTLCs.
5050         //
5051         // Alternatively, we may broadcast the previous commitment transaction, which should only
5052         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5053         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5054
5055         if announce_latest {
5056                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5057         } else {
5058                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5059         }
5060         let events = nodes[2].node.get_and_clear_pending_events();
5061         let close_event = if deliver_last_raa {
5062                 assert_eq!(events.len(), 2 + 6);
5063                 events.last().clone().unwrap()
5064         } else {
5065                 assert_eq!(events.len(), 1);
5066                 events.last().clone().unwrap()
5067         };
5068         match close_event {
5069                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5070                 _ => panic!("Unexpected event"),
5071         }
5072
5073         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5074         check_closed_broadcast!(nodes[2], true);
5075         if deliver_last_raa {
5076                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5077
5078                 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();
5079                 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5080         } else {
5081                 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5082                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5083                 } else {
5084                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5085                 };
5086
5087                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5088         }
5089         check_added_monitors!(nodes[2], 3);
5090
5091         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5092         assert_eq!(cs_msgs.len(), 2);
5093         let mut a_done = false;
5094         for msg in cs_msgs {
5095                 match msg {
5096                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5097                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5098                                 // should be failed-backwards here.
5099                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5100                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5101                                         for htlc in &updates.update_fail_htlcs {
5102                                                 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 });
5103                                         }
5104                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5105                                         assert!(!a_done);
5106                                         a_done = true;
5107                                         &nodes[0]
5108                                 } else {
5109                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5110                                         for htlc in &updates.update_fail_htlcs {
5111                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5112                                         }
5113                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5114                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5115                                         &nodes[1]
5116                                 };
5117                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5118                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5119                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5120                                 if announce_latest {
5121                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5122                                         if *node_id == nodes[0].node.get_our_node_id() {
5123                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5124                                         }
5125                                 }
5126                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5127                         },
5128                         _ => panic!("Unexpected event"),
5129                 }
5130         }
5131
5132         let as_events = nodes[0].node.get_and_clear_pending_events();
5133         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5134         let mut as_failds = HashSet::new();
5135         let mut as_updates = 0;
5136         for event in as_events.iter() {
5137                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref network_update, .. } = event {
5138                         assert!(as_failds.insert(*payment_hash));
5139                         if *payment_hash != payment_hash_2 {
5140                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5141                         } else {
5142                                 assert!(!payment_failed_permanently);
5143                         }
5144                         if network_update.is_some() {
5145                                 as_updates += 1;
5146                         }
5147                 } else { panic!("Unexpected event"); }
5148         }
5149         assert!(as_failds.contains(&payment_hash_1));
5150         assert!(as_failds.contains(&payment_hash_2));
5151         if announce_latest {
5152                 assert!(as_failds.contains(&payment_hash_3));
5153                 assert!(as_failds.contains(&payment_hash_5));
5154         }
5155         assert!(as_failds.contains(&payment_hash_6));
5156
5157         let bs_events = nodes[1].node.get_and_clear_pending_events();
5158         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5159         let mut bs_failds = HashSet::new();
5160         let mut bs_updates = 0;
5161         for event in bs_events.iter() {
5162                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref network_update, .. } = event {
5163                         assert!(bs_failds.insert(*payment_hash));
5164                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5165                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5166                         } else {
5167                                 assert!(!payment_failed_permanently);
5168                         }
5169                         if network_update.is_some() {
5170                                 bs_updates += 1;
5171                         }
5172                 } else { panic!("Unexpected event"); }
5173         }
5174         assert!(bs_failds.contains(&payment_hash_1));
5175         assert!(bs_failds.contains(&payment_hash_2));
5176         if announce_latest {
5177                 assert!(bs_failds.contains(&payment_hash_4));
5178         }
5179         assert!(bs_failds.contains(&payment_hash_5));
5180
5181         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5182         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5183         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5184         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5185         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5186         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5187 }
5188
5189 #[test]
5190 fn test_fail_backwards_latest_remote_announce_a() {
5191         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5192 }
5193
5194 #[test]
5195 fn test_fail_backwards_latest_remote_announce_b() {
5196         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5197 }
5198
5199 #[test]
5200 fn test_fail_backwards_previous_remote_announce() {
5201         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5202         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5203         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5204 }
5205
5206 #[test]
5207 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5208         let chanmon_cfgs = create_chanmon_cfgs(2);
5209         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5210         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5211         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5212
5213         // Create some initial channels
5214         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5215
5216         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5217         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5218         assert_eq!(local_txn[0].input.len(), 1);
5219         check_spends!(local_txn[0], chan_1.3);
5220
5221         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5222         mine_transaction(&nodes[0], &local_txn[0]);
5223         check_closed_broadcast!(nodes[0], true);
5224         check_added_monitors!(nodes[0], 1);
5225         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5226         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5227
5228         let htlc_timeout = {
5229                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5230                 assert_eq!(node_txn.len(), 2);
5231                 check_spends!(node_txn[0], chan_1.3);
5232                 assert_eq!(node_txn[1].input.len(), 1);
5233                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5234                 check_spends!(node_txn[1], local_txn[0]);
5235                 node_txn[1].clone()
5236         };
5237
5238         mine_transaction(&nodes[0], &htlc_timeout);
5239         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5240         expect_payment_failed!(nodes[0], our_payment_hash, false);
5241
5242         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5243         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5244         assert_eq!(spend_txn.len(), 3);
5245         check_spends!(spend_txn[0], local_txn[0]);
5246         assert_eq!(spend_txn[1].input.len(), 1);
5247         check_spends!(spend_txn[1], htlc_timeout);
5248         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5249         assert_eq!(spend_txn[2].input.len(), 2);
5250         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5251         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5252                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5253 }
5254
5255 #[test]
5256 fn test_key_derivation_params() {
5257         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5258         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5259         // let us re-derive the channel key set to then derive a delayed_payment_key.
5260
5261         let chanmon_cfgs = create_chanmon_cfgs(3);
5262
5263         // We manually create the node configuration to backup the seed.
5264         let seed = [42; 32];
5265         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5266         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);
5267         let network_graph = NetworkGraph::new(chanmon_cfgs[0].chain_source.genesis_hash, &chanmon_cfgs[0].logger);
5268         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() };
5269         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5270         node_cfgs.remove(0);
5271         node_cfgs.insert(0, node);
5272
5273         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5274         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5275
5276         // Create some initial channels
5277         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5278         // for node 0
5279         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5280         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5281         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5282
5283         // Ensure all nodes are at the same height
5284         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5285         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5286         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5287         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5288
5289         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5290         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5291         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5292         assert_eq!(local_txn_1[0].input.len(), 1);
5293         check_spends!(local_txn_1[0], chan_1.3);
5294
5295         // We check funding pubkey are unique
5296         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]));
5297         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]));
5298         if from_0_funding_key_0 == from_1_funding_key_0
5299             || from_0_funding_key_0 == from_1_funding_key_1
5300             || from_0_funding_key_1 == from_1_funding_key_0
5301             || from_0_funding_key_1 == from_1_funding_key_1 {
5302                 panic!("Funding pubkeys aren't unique");
5303         }
5304
5305         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5306         mine_transaction(&nodes[0], &local_txn_1[0]);
5307         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5308         check_closed_broadcast!(nodes[0], true);
5309         check_added_monitors!(nodes[0], 1);
5310         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5311
5312         let htlc_timeout = {
5313                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5314                 assert_eq!(node_txn[1].input.len(), 1);
5315                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5316                 check_spends!(node_txn[1], local_txn_1[0]);
5317                 node_txn[1].clone()
5318         };
5319
5320         mine_transaction(&nodes[0], &htlc_timeout);
5321         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5322         expect_payment_failed!(nodes[0], our_payment_hash, false);
5323
5324         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5325         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5326         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5327         assert_eq!(spend_txn.len(), 3);
5328         check_spends!(spend_txn[0], local_txn_1[0]);
5329         assert_eq!(spend_txn[1].input.len(), 1);
5330         check_spends!(spend_txn[1], htlc_timeout);
5331         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5332         assert_eq!(spend_txn[2].input.len(), 2);
5333         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5334         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5335                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5336 }
5337
5338 #[test]
5339 fn test_static_output_closing_tx() {
5340         let chanmon_cfgs = create_chanmon_cfgs(2);
5341         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5342         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5343         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5344
5345         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5346
5347         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5348         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5349
5350         mine_transaction(&nodes[0], &closing_tx);
5351         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5352         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5353
5354         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5355         assert_eq!(spend_txn.len(), 1);
5356         check_spends!(spend_txn[0], closing_tx);
5357
5358         mine_transaction(&nodes[1], &closing_tx);
5359         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5360         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5361
5362         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5363         assert_eq!(spend_txn.len(), 1);
5364         check_spends!(spend_txn[0], closing_tx);
5365 }
5366
5367 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5368         let chanmon_cfgs = create_chanmon_cfgs(2);
5369         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5370         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5371         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5372         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5373
5374         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5375
5376         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5377         // present in B's local commitment transaction, but none of A's commitment transactions.
5378         nodes[1].node.claim_funds(payment_preimage);
5379         check_added_monitors!(nodes[1], 1);
5380         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5381
5382         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5383         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5384         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5385
5386         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5387         check_added_monitors!(nodes[0], 1);
5388         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5389         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5390         check_added_monitors!(nodes[1], 1);
5391
5392         let starting_block = nodes[1].best_block_info();
5393         let mut block = Block {
5394                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5395                 txdata: vec![],
5396         };
5397         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5398                 connect_block(&nodes[1], &block);
5399                 block.header.prev_blockhash = block.block_hash();
5400         }
5401         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5402         check_closed_broadcast!(nodes[1], true);
5403         check_added_monitors!(nodes[1], 1);
5404         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5405 }
5406
5407 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5408         let chanmon_cfgs = create_chanmon_cfgs(2);
5409         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5410         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5411         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5412         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5413
5414         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5415         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
5416         check_added_monitors!(nodes[0], 1);
5417
5418         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5419
5420         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5421         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5422         // to "time out" the HTLC.
5423
5424         let starting_block = nodes[1].best_block_info();
5425         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5426
5427         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5428                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5429                 header.prev_blockhash = header.block_hash();
5430         }
5431         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5432         check_closed_broadcast!(nodes[0], true);
5433         check_added_monitors!(nodes[0], 1);
5434         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5435 }
5436
5437 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5438         let chanmon_cfgs = create_chanmon_cfgs(3);
5439         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5440         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5441         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5442         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5443
5444         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5445         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5446         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5447         // actually revoked.
5448         let htlc_value = if use_dust { 50000 } else { 3000000 };
5449         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5450         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5451         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5452         check_added_monitors!(nodes[1], 1);
5453
5454         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5455         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5456         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5457         check_added_monitors!(nodes[0], 1);
5458         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5459         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5460         check_added_monitors!(nodes[1], 1);
5461         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5462         check_added_monitors!(nodes[1], 1);
5463         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5464
5465         if check_revoke_no_close {
5466                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5467                 check_added_monitors!(nodes[0], 1);
5468         }
5469
5470         let starting_block = nodes[1].best_block_info();
5471         let mut block = Block {
5472                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5473                 txdata: vec![],
5474         };
5475         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5476                 connect_block(&nodes[0], &block);
5477                 block.header.prev_blockhash = block.block_hash();
5478         }
5479         if !check_revoke_no_close {
5480                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5481                 check_closed_broadcast!(nodes[0], true);
5482                 check_added_monitors!(nodes[0], 1);
5483                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5484         } else {
5485                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5486         }
5487 }
5488
5489 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5490 // There are only a few cases to test here:
5491 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5492 //    broadcastable commitment transactions result in channel closure,
5493 //  * its included in an unrevoked-but-previous remote commitment transaction,
5494 //  * its included in the latest remote or local commitment transactions.
5495 // We test each of the three possible commitment transactions individually and use both dust and
5496 // non-dust HTLCs.
5497 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5498 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5499 // tested for at least one of the cases in other tests.
5500 #[test]
5501 fn htlc_claim_single_commitment_only_a() {
5502         do_htlc_claim_local_commitment_only(true);
5503         do_htlc_claim_local_commitment_only(false);
5504
5505         do_htlc_claim_current_remote_commitment_only(true);
5506         do_htlc_claim_current_remote_commitment_only(false);
5507 }
5508
5509 #[test]
5510 fn htlc_claim_single_commitment_only_b() {
5511         do_htlc_claim_previous_remote_commitment_only(true, false);
5512         do_htlc_claim_previous_remote_commitment_only(false, false);
5513         do_htlc_claim_previous_remote_commitment_only(true, true);
5514         do_htlc_claim_previous_remote_commitment_only(false, true);
5515 }
5516
5517 #[test]
5518 #[should_panic]
5519 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5520         let chanmon_cfgs = create_chanmon_cfgs(2);
5521         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5522         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5523         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5524         // Force duplicate randomness for every get-random call
5525         for node in nodes.iter() {
5526                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5527         }
5528
5529         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5530         let channel_value_satoshis=10000;
5531         let push_msat=10001;
5532         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5533         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5534         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &node0_to_1_send_open_channel);
5535         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5536
5537         // Create a second channel with the same random values. This used to panic due to a colliding
5538         // channel_id, but now panics due to a colliding outbound SCID alias.
5539         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5540 }
5541
5542 #[test]
5543 fn bolt2_open_channel_sending_node_checks_part2() {
5544         let chanmon_cfgs = create_chanmon_cfgs(2);
5545         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5546         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5547         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5548
5549         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5550         let channel_value_satoshis=2^24;
5551         let push_msat=10001;
5552         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5553
5554         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5555         let channel_value_satoshis=10000;
5556         // Test when push_msat is equal to 1000 * funding_satoshis.
5557         let push_msat=1000*channel_value_satoshis+1;
5558         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5559
5560         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5561         let channel_value_satoshis=10000;
5562         let push_msat=10001;
5563         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
5564         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5565         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5566
5567         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5568         // 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
5569         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5570
5571         // 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.
5572         assert!(BREAKDOWN_TIMEOUT>0);
5573         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5574
5575         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5576         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5577         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5578
5579         // 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.
5580         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5581         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5582         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5583         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5584         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5585 }
5586
5587 #[test]
5588 fn bolt2_open_channel_sane_dust_limit() {
5589         let chanmon_cfgs = create_chanmon_cfgs(2);
5590         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5591         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5592         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5593
5594         let channel_value_satoshis=1000000;
5595         let push_msat=10001;
5596         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5597         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5598         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5599         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5600
5601         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &node0_to_1_send_open_channel);
5602         let events = nodes[1].node.get_and_clear_pending_msg_events();
5603         let err_msg = match events[0] {
5604                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5605                         msg.clone()
5606                 },
5607                 _ => panic!("Unexpected event"),
5608         };
5609         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5610 }
5611
5612 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5613 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5614 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5615 // is no longer affordable once it's freed.
5616 #[test]
5617 fn test_fail_holding_cell_htlc_upon_free() {
5618         let chanmon_cfgs = create_chanmon_cfgs(2);
5619         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5620         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5621         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5622         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5623
5624         // First nodes[0] generates an update_fee, setting the channel's
5625         // pending_update_fee.
5626         {
5627                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5628                 *feerate_lock += 20;
5629         }
5630         nodes[0].node.timer_tick_occurred();
5631         check_added_monitors!(nodes[0], 1);
5632
5633         let events = nodes[0].node.get_and_clear_pending_msg_events();
5634         assert_eq!(events.len(), 1);
5635         let (update_msg, commitment_signed) = match events[0] {
5636                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5637                         (update_fee.as_ref(), commitment_signed)
5638                 },
5639                 _ => panic!("Unexpected event"),
5640         };
5641
5642         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5643
5644         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5645         let channel_reserve = chan_stat.channel_reserve_msat;
5646         let feerate = get_feerate!(nodes[0], chan.2);
5647         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
5648
5649         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5650         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5651         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5652
5653         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5654         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5655         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5656         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5657
5658         // Flush the pending fee update.
5659         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5660         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5661         check_added_monitors!(nodes[1], 1);
5662         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5663         check_added_monitors!(nodes[0], 1);
5664
5665         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5666         // HTLC, but now that the fee has been raised the payment will now fail, causing
5667         // us to surface its failure to the user.
5668         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5669         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5670         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);
5671         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 {}",
5672                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5673         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5674
5675         // Check that the payment failed to be sent out.
5676         let events = nodes[0].node.get_and_clear_pending_events();
5677         assert_eq!(events.len(), 1);
5678         match &events[0] {
5679                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update, ref all_paths_failed, ref short_channel_id, .. } => {
5680                         assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5681                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5682                         assert_eq!(*payment_failed_permanently, false);
5683                         assert_eq!(*all_paths_failed, true);
5684                         assert_eq!(*network_update, None);
5685                         assert_eq!(*short_channel_id, Some(route.paths[0][0].short_channel_id));
5686                 },
5687                 _ => panic!("Unexpected event"),
5688         }
5689 }
5690
5691 // Test that if multiple HTLCs are released from the holding cell and one is
5692 // valid but the other is no longer valid upon release, the valid HTLC can be
5693 // successfully completed while the other one fails as expected.
5694 #[test]
5695 fn test_free_and_fail_holding_cell_htlcs() {
5696         let chanmon_cfgs = create_chanmon_cfgs(2);
5697         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5698         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5699         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5700         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5701
5702         // First nodes[0] generates an update_fee, setting the channel's
5703         // pending_update_fee.
5704         {
5705                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5706                 *feerate_lock += 200;
5707         }
5708         nodes[0].node.timer_tick_occurred();
5709         check_added_monitors!(nodes[0], 1);
5710
5711         let events = nodes[0].node.get_and_clear_pending_msg_events();
5712         assert_eq!(events.len(), 1);
5713         let (update_msg, commitment_signed) = match events[0] {
5714                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5715                         (update_fee.as_ref(), commitment_signed)
5716                 },
5717                 _ => panic!("Unexpected event"),
5718         };
5719
5720         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5721
5722         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5723         let channel_reserve = chan_stat.channel_reserve_msat;
5724         let feerate = get_feerate!(nodes[0], chan.2);
5725         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
5726
5727         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5728         let amt_1 = 20000;
5729         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
5730         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5731         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5732
5733         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5734         nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5735         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5736         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5737         let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5738         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2), payment_id_2).unwrap();
5739         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5740         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5741
5742         // Flush the pending fee update.
5743         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5744         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5745         check_added_monitors!(nodes[1], 1);
5746         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5747         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5748         check_added_monitors!(nodes[0], 2);
5749
5750         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5751         // but now that the fee has been raised the second payment will now fail, causing us
5752         // to surface its failure to the user. The first payment should succeed.
5753         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5754         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5755         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);
5756         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 {}",
5757                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5758         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5759
5760         // Check that the second payment failed to be sent out.
5761         let events = nodes[0].node.get_and_clear_pending_events();
5762         assert_eq!(events.len(), 1);
5763         match &events[0] {
5764                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update, ref all_paths_failed, ref short_channel_id, .. } => {
5765                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5766                         assert_eq!(payment_hash_2.clone(), *payment_hash);
5767                         assert_eq!(*payment_failed_permanently, false);
5768                         assert_eq!(*all_paths_failed, true);
5769                         assert_eq!(*network_update, None);
5770                         assert_eq!(*short_channel_id, Some(route_2.paths[0][0].short_channel_id));
5771                 },
5772                 _ => panic!("Unexpected event"),
5773         }
5774
5775         // Complete the first payment and the RAA from the fee update.
5776         let (payment_event, send_raa_event) = {
5777                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5778                 assert_eq!(msgs.len(), 2);
5779                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5780         };
5781         let raa = match send_raa_event {
5782                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5783                 _ => panic!("Unexpected event"),
5784         };
5785         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5786         check_added_monitors!(nodes[1], 1);
5787         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5788         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5789         let events = nodes[1].node.get_and_clear_pending_events();
5790         assert_eq!(events.len(), 1);
5791         match events[0] {
5792                 Event::PendingHTLCsForwardable { .. } => {},
5793                 _ => panic!("Unexpected event"),
5794         }
5795         nodes[1].node.process_pending_htlc_forwards();
5796         let events = nodes[1].node.get_and_clear_pending_events();
5797         assert_eq!(events.len(), 1);
5798         match events[0] {
5799                 Event::PaymentReceived { .. } => {},
5800                 _ => panic!("Unexpected event"),
5801         }
5802         nodes[1].node.claim_funds(payment_preimage_1);
5803         check_added_monitors!(nodes[1], 1);
5804         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5805
5806         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5807         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5808         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5809         expect_payment_sent!(nodes[0], payment_preimage_1);
5810 }
5811
5812 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
5813 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
5814 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
5815 // once it's freed.
5816 #[test]
5817 fn test_fail_holding_cell_htlc_upon_free_multihop() {
5818         let chanmon_cfgs = create_chanmon_cfgs(3);
5819         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5820         // When this test was written, the default base fee floated based on the HTLC count.
5821         // It is now fixed, so we simply set the fee to the expected value here.
5822         let mut config = test_default_channel_config();
5823         config.channel_config.forwarding_fee_base_msat = 196;
5824         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5825         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5826         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5827         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5828
5829         // First nodes[1] generates an update_fee, setting the channel's
5830         // pending_update_fee.
5831         {
5832                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
5833                 *feerate_lock += 20;
5834         }
5835         nodes[1].node.timer_tick_occurred();
5836         check_added_monitors!(nodes[1], 1);
5837
5838         let events = nodes[1].node.get_and_clear_pending_msg_events();
5839         assert_eq!(events.len(), 1);
5840         let (update_msg, commitment_signed) = match events[0] {
5841                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5842                         (update_fee.as_ref(), commitment_signed)
5843                 },
5844                 _ => panic!("Unexpected event"),
5845         };
5846
5847         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
5848
5849         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
5850         let channel_reserve = chan_stat.channel_reserve_msat;
5851         let feerate = get_feerate!(nodes[0], chan_0_1.2);
5852         let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
5853
5854         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5855         let feemsat = 239;
5856         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
5857         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
5858         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
5859         let payment_event = {
5860                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5861                 check_added_monitors!(nodes[0], 1);
5862
5863                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5864                 assert_eq!(events.len(), 1);
5865
5866                 SendEvent::from_event(events.remove(0))
5867         };
5868         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5869         check_added_monitors!(nodes[1], 0);
5870         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5871         expect_pending_htlcs_forwardable!(nodes[1]);
5872
5873         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
5874         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5875
5876         // Flush the pending fee update.
5877         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
5878         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5879         check_added_monitors!(nodes[2], 1);
5880         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
5881         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
5882         check_added_monitors!(nodes[1], 2);
5883
5884         // A final RAA message is generated to finalize the fee update.
5885         let events = nodes[1].node.get_and_clear_pending_msg_events();
5886         assert_eq!(events.len(), 1);
5887
5888         let raa_msg = match &events[0] {
5889                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
5890                         msg.clone()
5891                 },
5892                 _ => panic!("Unexpected event"),
5893         };
5894
5895         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
5896         check_added_monitors!(nodes[2], 1);
5897         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
5898
5899         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
5900         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
5901         assert_eq!(process_htlc_forwards_event.len(), 2);
5902         match &process_htlc_forwards_event[0] {
5903                 &Event::PendingHTLCsForwardable { .. } => {},
5904                 _ => panic!("Unexpected event"),
5905         }
5906
5907         // In response, we call ChannelManager's process_pending_htlc_forwards
5908         nodes[1].node.process_pending_htlc_forwards();
5909         check_added_monitors!(nodes[1], 1);
5910
5911         // This causes the HTLC to be failed backwards.
5912         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
5913         assert_eq!(fail_event.len(), 1);
5914         let (fail_msg, commitment_signed) = match &fail_event[0] {
5915                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
5916                         assert_eq!(updates.update_add_htlcs.len(), 0);
5917                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
5918                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
5919                         assert_eq!(updates.update_fail_htlcs.len(), 1);
5920                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
5921                 },
5922                 _ => panic!("Unexpected event"),
5923         };
5924
5925         // Pass the failure messages back to nodes[0].
5926         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5927         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5928
5929         // Complete the HTLC failure+removal process.
5930         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5931         check_added_monitors!(nodes[0], 1);
5932         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5933         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
5934         check_added_monitors!(nodes[1], 2);
5935         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
5936         assert_eq!(final_raa_event.len(), 1);
5937         let raa = match &final_raa_event[0] {
5938                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
5939                 _ => panic!("Unexpected event"),
5940         };
5941         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
5942         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
5943         check_added_monitors!(nodes[0], 1);
5944 }
5945
5946 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
5947 // 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.
5948 //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.
5949
5950 #[test]
5951 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
5952         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
5953         let chanmon_cfgs = create_chanmon_cfgs(2);
5954         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5955         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5956         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5957         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5958
5959         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
5960         route.paths[0][0].fee_msat = 100;
5961
5962         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 },
5963                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
5964         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5965         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
5966 }
5967
5968 #[test]
5969 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
5970         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
5971         let chanmon_cfgs = create_chanmon_cfgs(2);
5972         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5973         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5974         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5975         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5976
5977         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
5978         route.paths[0][0].fee_msat = 0;
5979         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 },
5980                 assert_eq!(err, "Cannot send 0-msat HTLC"));
5981
5982         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5983         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
5984 }
5985
5986 #[test]
5987 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
5988         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
5989         let chanmon_cfgs = create_chanmon_cfgs(2);
5990         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5991         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5992         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5993         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
5994
5995         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
5996         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5997         check_added_monitors!(nodes[0], 1);
5998         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5999         updates.update_add_htlcs[0].amount_msat = 0;
6000
6001         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6002         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6003         check_closed_broadcast!(nodes[1], true).unwrap();
6004         check_added_monitors!(nodes[1], 1);
6005         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6006 }
6007
6008 #[test]
6009 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6010         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6011         //It is enforced when constructing a route.
6012         let chanmon_cfgs = create_chanmon_cfgs(2);
6013         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6014         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6015         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6016         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6017
6018         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
6019                 .with_features(channelmanager::provided_invoice_features());
6020         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6021         route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6022         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::RouteError { ref err },
6023                 assert_eq!(err, &"Channel CLTV overflowed?"));
6024 }
6025
6026 #[test]
6027 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6028         //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.
6029         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6030         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6031         let chanmon_cfgs = create_chanmon_cfgs(2);
6032         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6033         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6034         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6035         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6036         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6037
6038         for i in 0..max_accepted_htlcs {
6039                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6040                 let payment_event = {
6041                         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6042                         check_added_monitors!(nodes[0], 1);
6043
6044                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6045                         assert_eq!(events.len(), 1);
6046                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6047                                 assert_eq!(htlcs[0].htlc_id, i);
6048                         } else {
6049                                 assert!(false);
6050                         }
6051                         SendEvent::from_event(events.remove(0))
6052                 };
6053                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6054                 check_added_monitors!(nodes[1], 0);
6055                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6056
6057                 expect_pending_htlcs_forwardable!(nodes[1]);
6058                 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6059         }
6060         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6061         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 },
6062                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6063
6064         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6065         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6066 }
6067
6068 #[test]
6069 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6070         //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.
6071         let chanmon_cfgs = create_chanmon_cfgs(2);
6072         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6073         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6074         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6075         let channel_value = 100000;
6076         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6077         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6078
6079         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6080
6081         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6082         // Manually create a route over our max in flight (which our router normally automatically
6083         // limits us to.
6084         route.paths[0][0].fee_msat =  max_in_flight + 1;
6085         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 },
6086                 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)));
6087
6088         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6089         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);
6090
6091         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6092 }
6093
6094 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6095 #[test]
6096 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6097         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6098         let chanmon_cfgs = create_chanmon_cfgs(2);
6099         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6100         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6101         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6102         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6103         let htlc_minimum_msat: u64;
6104         {
6105                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6106                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6107                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6108         }
6109
6110         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6111         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6112         check_added_monitors!(nodes[0], 1);
6113         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6114         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6115         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6116         assert!(nodes[1].node.list_channels().is_empty());
6117         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6118         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()));
6119         check_added_monitors!(nodes[1], 1);
6120         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6121 }
6122
6123 #[test]
6124 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6125         //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
6126         let chanmon_cfgs = create_chanmon_cfgs(2);
6127         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6128         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6129         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6130         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6131
6132         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6133         let channel_reserve = chan_stat.channel_reserve_msat;
6134         let feerate = get_feerate!(nodes[0], chan.2);
6135         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6136         // The 2* and +1 are for the fee spike reserve.
6137         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6138
6139         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6140         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6141         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6142         check_added_monitors!(nodes[0], 1);
6143         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6144
6145         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6146         // at this time channel-initiatee receivers are not required to enforce that senders
6147         // respect the fee_spike_reserve.
6148         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6149         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6150
6151         assert!(nodes[1].node.list_channels().is_empty());
6152         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6153         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6154         check_added_monitors!(nodes[1], 1);
6155         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6156 }
6157
6158 #[test]
6159 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6160         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6161         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6162         let chanmon_cfgs = create_chanmon_cfgs(2);
6163         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6164         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6165         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6166         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6167
6168         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6169         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6170         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6171         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6172         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6173         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6174
6175         let mut msg = msgs::UpdateAddHTLC {
6176                 channel_id: chan.2,
6177                 htlc_id: 0,
6178                 amount_msat: 1000,
6179                 payment_hash: our_payment_hash,
6180                 cltv_expiry: htlc_cltv,
6181                 onion_routing_packet: onion_packet.clone(),
6182         };
6183
6184         for i in 0..super::channel::OUR_MAX_HTLCS {
6185                 msg.htlc_id = i as u64;
6186                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6187         }
6188         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6189         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6190
6191         assert!(nodes[1].node.list_channels().is_empty());
6192         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6193         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6194         check_added_monitors!(nodes[1], 1);
6195         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6196 }
6197
6198 #[test]
6199 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6200         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6201         let chanmon_cfgs = create_chanmon_cfgs(2);
6202         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6203         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6204         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6205         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6206
6207         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6208         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6209         check_added_monitors!(nodes[0], 1);
6210         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6211         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6212         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6213
6214         assert!(nodes[1].node.list_channels().is_empty());
6215         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6216         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6217         check_added_monitors!(nodes[1], 1);
6218         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6219 }
6220
6221 #[test]
6222 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6223         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6224         let chanmon_cfgs = create_chanmon_cfgs(2);
6225         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6226         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6227         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6228
6229         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6230         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6231         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6232         check_added_monitors!(nodes[0], 1);
6233         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6234         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6235         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6236
6237         assert!(nodes[1].node.list_channels().is_empty());
6238         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6239         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6240         check_added_monitors!(nodes[1], 1);
6241         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6242 }
6243
6244 #[test]
6245 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6246         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6247         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6248         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6249         let chanmon_cfgs = create_chanmon_cfgs(2);
6250         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6251         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6252         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6253
6254         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6255         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6256         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6257         check_added_monitors!(nodes[0], 1);
6258         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6259         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6260
6261         //Disconnect and Reconnect
6262         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6263         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6264         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
6265         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6266         assert_eq!(reestablish_1.len(), 1);
6267         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
6268         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6269         assert_eq!(reestablish_2.len(), 1);
6270         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6271         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6272         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6273         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6274
6275         //Resend HTLC
6276         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6277         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6278         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6279         check_added_monitors!(nodes[1], 1);
6280         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6281
6282         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6283
6284         assert!(nodes[1].node.list_channels().is_empty());
6285         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6286         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6287         check_added_monitors!(nodes[1], 1);
6288         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6289 }
6290
6291 #[test]
6292 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6293         //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.
6294
6295         let chanmon_cfgs = create_chanmon_cfgs(2);
6296         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6297         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6298         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6299         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6300         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6301         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6302
6303         check_added_monitors!(nodes[0], 1);
6304         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6305         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6306
6307         let update_msg = msgs::UpdateFulfillHTLC{
6308                 channel_id: chan.2,
6309                 htlc_id: 0,
6310                 payment_preimage: our_payment_preimage,
6311         };
6312
6313         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6314
6315         assert!(nodes[0].node.list_channels().is_empty());
6316         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6317         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()));
6318         check_added_monitors!(nodes[0], 1);
6319         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6320 }
6321
6322 #[test]
6323 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6324         //BOLT 2 Requirement: until the corresponding HTLC is irrevocably committed in both sides' commitment transactions:     MUST NOT send an update_fulfill_htlc, update_fail_htlc, or update_fail_malformed_htlc.
6325
6326         let chanmon_cfgs = create_chanmon_cfgs(2);
6327         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6328         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6329         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6330         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6331
6332         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6333         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6334         check_added_monitors!(nodes[0], 1);
6335         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6336         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6337
6338         let update_msg = msgs::UpdateFailHTLC{
6339                 channel_id: chan.2,
6340                 htlc_id: 0,
6341                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6342         };
6343
6344         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6345
6346         assert!(nodes[0].node.list_channels().is_empty());
6347         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6348         assert!(regex::Regex::new(r"Remote tried to fulfill/fail HTLC \(\d+\) before it had been committed").unwrap().is_match(err_msg.data.as_str()));
6349         check_added_monitors!(nodes[0], 1);
6350         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6351 }
6352
6353 #[test]
6354 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6355         //BOLT 2 Requirement: until the corresponding HTLC is irrevocably committed in both sides' commitment transactions:     MUST NOT send an update_fulfill_htlc, update_fail_htlc, or update_fail_malformed_htlc.
6356
6357         let chanmon_cfgs = create_chanmon_cfgs(2);
6358         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6359         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6360         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6361         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6362
6363         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6364         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6365         check_added_monitors!(nodes[0], 1);
6366         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6367         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6368         let update_msg = msgs::UpdateFailMalformedHTLC{
6369                 channel_id: chan.2,
6370                 htlc_id: 0,
6371                 sha256_of_onion: [1; 32],
6372                 failure_code: 0x8000,
6373         };
6374
6375         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6376
6377         assert!(nodes[0].node.list_channels().is_empty());
6378         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6379         assert!(regex::Regex::new(r"Remote tried to fulfill/fail HTLC \(\d+\) before it had been committed").unwrap().is_match(err_msg.data.as_str()));
6380         check_added_monitors!(nodes[0], 1);
6381         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6382 }
6383
6384 #[test]
6385 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6386         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6387
6388         let chanmon_cfgs = create_chanmon_cfgs(2);
6389         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6390         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6391         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6392         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6393
6394         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6395
6396         nodes[1].node.claim_funds(our_payment_preimage);
6397         check_added_monitors!(nodes[1], 1);
6398         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6399
6400         let events = nodes[1].node.get_and_clear_pending_msg_events();
6401         assert_eq!(events.len(), 1);
6402         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6403                 match events[0] {
6404                         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, .. } } => {
6405                                 assert!(update_add_htlcs.is_empty());
6406                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6407                                 assert!(update_fail_htlcs.is_empty());
6408                                 assert!(update_fail_malformed_htlcs.is_empty());
6409                                 assert!(update_fee.is_none());
6410                                 update_fulfill_htlcs[0].clone()
6411                         },
6412                         _ => panic!("Unexpected event"),
6413                 }
6414         };
6415
6416         update_fulfill_msg.htlc_id = 1;
6417
6418         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6419
6420         assert!(nodes[0].node.list_channels().is_empty());
6421         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6422         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6423         check_added_monitors!(nodes[0], 1);
6424         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6425 }
6426
6427 #[test]
6428 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6429         //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.
6430
6431         let chanmon_cfgs = create_chanmon_cfgs(2);
6432         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6433         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6434         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6435         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6436
6437         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6438
6439         nodes[1].node.claim_funds(our_payment_preimage);
6440         check_added_monitors!(nodes[1], 1);
6441         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6442
6443         let events = nodes[1].node.get_and_clear_pending_msg_events();
6444         assert_eq!(events.len(), 1);
6445         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6446                 match events[0] {
6447                         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, .. } } => {
6448                                 assert!(update_add_htlcs.is_empty());
6449                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6450                                 assert!(update_fail_htlcs.is_empty());
6451                                 assert!(update_fail_malformed_htlcs.is_empty());
6452                                 assert!(update_fee.is_none());
6453                                 update_fulfill_htlcs[0].clone()
6454                         },
6455                         _ => panic!("Unexpected event"),
6456                 }
6457         };
6458
6459         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6460
6461         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6462
6463         assert!(nodes[0].node.list_channels().is_empty());
6464         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6465         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6466         check_added_monitors!(nodes[0], 1);
6467         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6468 }
6469
6470 #[test]
6471 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6472         //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.
6473
6474         let chanmon_cfgs = create_chanmon_cfgs(2);
6475         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6476         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6477         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6478         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6479
6480         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6481         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6482         check_added_monitors!(nodes[0], 1);
6483
6484         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6485         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6486
6487         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6488         check_added_monitors!(nodes[1], 0);
6489         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6490
6491         let events = nodes[1].node.get_and_clear_pending_msg_events();
6492
6493         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6494                 match events[0] {
6495                         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, .. } } => {
6496                                 assert!(update_add_htlcs.is_empty());
6497                                 assert!(update_fulfill_htlcs.is_empty());
6498                                 assert!(update_fail_htlcs.is_empty());
6499                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6500                                 assert!(update_fee.is_none());
6501                                 update_fail_malformed_htlcs[0].clone()
6502                         },
6503                         _ => panic!("Unexpected event"),
6504                 }
6505         };
6506         update_msg.failure_code &= !0x8000;
6507         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6508
6509         assert!(nodes[0].node.list_channels().is_empty());
6510         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6511         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6512         check_added_monitors!(nodes[0], 1);
6513         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6514 }
6515
6516 #[test]
6517 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6518         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6519         //    * 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.
6520
6521         let chanmon_cfgs = create_chanmon_cfgs(3);
6522         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6523         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6524         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6525         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6526         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6527
6528         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6529
6530         //First hop
6531         let mut payment_event = {
6532                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6533                 check_added_monitors!(nodes[0], 1);
6534                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6535                 assert_eq!(events.len(), 1);
6536                 SendEvent::from_event(events.remove(0))
6537         };
6538         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6539         check_added_monitors!(nodes[1], 0);
6540         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6541         expect_pending_htlcs_forwardable!(nodes[1]);
6542         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6543         assert_eq!(events_2.len(), 1);
6544         check_added_monitors!(nodes[1], 1);
6545         payment_event = SendEvent::from_event(events_2.remove(0));
6546         assert_eq!(payment_event.msgs.len(), 1);
6547
6548         //Second Hop
6549         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6550         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6551         check_added_monitors!(nodes[2], 0);
6552         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6553
6554         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6555         assert_eq!(events_3.len(), 1);
6556         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6557                 match events_3[0] {
6558                         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 } } => {
6559                                 assert!(update_add_htlcs.is_empty());
6560                                 assert!(update_fulfill_htlcs.is_empty());
6561                                 assert!(update_fail_htlcs.is_empty());
6562                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6563                                 assert!(update_fee.is_none());
6564                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6565                         },
6566                         _ => panic!("Unexpected event"),
6567                 }
6568         };
6569
6570         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6571
6572         check_added_monitors!(nodes[1], 0);
6573         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6574         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 }]);
6575         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6576         assert_eq!(events_4.len(), 1);
6577
6578         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6579         match events_4[0] {
6580                 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, .. } } => {
6581                         assert!(update_add_htlcs.is_empty());
6582                         assert!(update_fulfill_htlcs.is_empty());
6583                         assert_eq!(update_fail_htlcs.len(), 1);
6584                         assert!(update_fail_malformed_htlcs.is_empty());
6585                         assert!(update_fee.is_none());
6586                 },
6587                 _ => panic!("Unexpected event"),
6588         };
6589
6590         check_added_monitors!(nodes[1], 1);
6591 }
6592
6593 #[test]
6594 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6595         let chanmon_cfgs = create_chanmon_cfgs(3);
6596         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6597         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6598         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6599         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6600         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6601
6602         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6603
6604         // First hop
6605         let mut payment_event = {
6606                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6607                 check_added_monitors!(nodes[0], 1);
6608                 SendEvent::from_node(&nodes[0])
6609         };
6610
6611         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6612         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6613         expect_pending_htlcs_forwardable!(nodes[1]);
6614         check_added_monitors!(nodes[1], 1);
6615         payment_event = SendEvent::from_node(&nodes[1]);
6616         assert_eq!(payment_event.msgs.len(), 1);
6617
6618         // Second Hop
6619         payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6620         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6621         check_added_monitors!(nodes[2], 0);
6622         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6623
6624         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6625         assert_eq!(events_3.len(), 1);
6626         match events_3[0] {
6627                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6628                         let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6629                         // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6630                         update_msg.failure_code |= 0x2000;
6631
6632                         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6633                         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6634                 },
6635                 _ => panic!("Unexpected event"),
6636         }
6637
6638         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6639                 vec![HTLCDestination::NextHopChannel {
6640                         node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6641         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6642         assert_eq!(events_4.len(), 1);
6643         check_added_monitors!(nodes[1], 1);
6644
6645         match events_4[0] {
6646                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6647                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6648                         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6649                 },
6650                 _ => panic!("Unexpected event"),
6651         }
6652
6653         let events_5 = nodes[0].node.get_and_clear_pending_events();
6654         assert_eq!(events_5.len(), 1);
6655
6656         // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6657         // the node originating the error to its next hop.
6658         match events_5[0] {
6659                 Event::PaymentPathFailed { network_update:
6660                         Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }), error_code, ..
6661                 } => {
6662                         assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6663                         assert!(is_permanent);
6664                         assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6665                 },
6666                 _ => panic!("Unexpected event"),
6667         }
6668
6669         // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6670 }
6671
6672 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6673         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6674         // 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
6675         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6676
6677         let mut chanmon_cfgs = create_chanmon_cfgs(2);
6678         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6679         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6680         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6681         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6682         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6683
6684         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6685
6686         // We route 2 dust-HTLCs between A and B
6687         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6688         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6689         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6690
6691         // Cache one local commitment tx as previous
6692         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6693
6694         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6695         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6696         check_added_monitors!(nodes[1], 0);
6697         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6698         check_added_monitors!(nodes[1], 1);
6699
6700         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6701         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6702         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6703         check_added_monitors!(nodes[0], 1);
6704
6705         // Cache one local commitment tx as lastest
6706         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6707
6708         let events = nodes[0].node.get_and_clear_pending_msg_events();
6709         match events[0] {
6710                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6711                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6712                 },
6713                 _ => panic!("Unexpected event"),
6714         }
6715         match events[1] {
6716                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6717                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6718                 },
6719                 _ => panic!("Unexpected event"),
6720         }
6721
6722         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6723         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6724         if announce_latest {
6725                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6726         } else {
6727                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6728         }
6729
6730         check_closed_broadcast!(nodes[0], true);
6731         check_added_monitors!(nodes[0], 1);
6732         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6733
6734         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6735         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6736         let events = nodes[0].node.get_and_clear_pending_events();
6737         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6738         assert_eq!(events.len(), 2);
6739         let mut first_failed = false;
6740         for event in events {
6741                 match event {
6742                         Event::PaymentPathFailed { payment_hash, .. } => {
6743                                 if payment_hash == payment_hash_1 {
6744                                         assert!(!first_failed);
6745                                         first_failed = true;
6746                                 } else {
6747                                         assert_eq!(payment_hash, payment_hash_2);
6748                                 }
6749                         }
6750                         _ => panic!("Unexpected event"),
6751                 }
6752         }
6753 }
6754
6755 #[test]
6756 fn test_failure_delay_dust_htlc_local_commitment() {
6757         do_test_failure_delay_dust_htlc_local_commitment(true);
6758         do_test_failure_delay_dust_htlc_local_commitment(false);
6759 }
6760
6761 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6762         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6763         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6764         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6765         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6766         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6767         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6768
6769         let chanmon_cfgs = create_chanmon_cfgs(3);
6770         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6771         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6772         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6773         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6774
6775         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6776
6777         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6778         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6779
6780         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6781         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6782
6783         // We revoked bs_commitment_tx
6784         if revoked {
6785                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6786                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6787         }
6788
6789         let mut timeout_tx = Vec::new();
6790         if local {
6791                 // We fail dust-HTLC 1 by broadcast of local commitment tx
6792                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
6793                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6794                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6795                 expect_payment_failed!(nodes[0], dust_hash, false);
6796
6797                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
6798                 check_closed_broadcast!(nodes[0], true);
6799                 check_added_monitors!(nodes[0], 1);
6800                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6801                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
6802                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6803                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6804                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6805                 mine_transaction(&nodes[0], &timeout_tx[0]);
6806                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6807                 expect_payment_failed!(nodes[0], non_dust_hash, false);
6808         } else {
6809                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6810                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
6811                 check_closed_broadcast!(nodes[0], true);
6812                 check_added_monitors!(nodes[0], 1);
6813                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6814                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6815
6816                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
6817                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
6818                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
6819                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
6820                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
6821                 // dust HTLC should have been failed.
6822                 expect_payment_failed!(nodes[0], dust_hash, false);
6823
6824                 if !revoked {
6825                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6826                 } else {
6827                         assert_eq!(timeout_tx[0].lock_time.0, 0);
6828                 }
6829                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
6830                 mine_transaction(&nodes[0], &timeout_tx[0]);
6831                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6832                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6833                 expect_payment_failed!(nodes[0], non_dust_hash, false);
6834         }
6835 }
6836
6837 #[test]
6838 fn test_sweep_outbound_htlc_failure_update() {
6839         do_test_sweep_outbound_htlc_failure_update(false, true);
6840         do_test_sweep_outbound_htlc_failure_update(false, false);
6841         do_test_sweep_outbound_htlc_failure_update(true, false);
6842 }
6843
6844 #[test]
6845 fn test_user_configurable_csv_delay() {
6846         // We test our channel constructors yield errors when we pass them absurd csv delay
6847
6848         let mut low_our_to_self_config = UserConfig::default();
6849         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
6850         let mut high_their_to_self_config = UserConfig::default();
6851         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
6852         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6853         let chanmon_cfgs = create_chanmon_cfgs(2);
6854         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6855         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6856         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6857
6858         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6859         if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6860                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), 1000000, 1000000, 0,
6861                 &low_our_to_self_config, 0, 42)
6862         {
6863                 match error {
6864                         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())); },
6865                         _ => panic!("Unexpected event"),
6866                 }
6867         } else { assert!(false) }
6868
6869         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6870         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6871         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6872         open_channel.to_self_delay = 200;
6873         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6874                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), &open_channel, 0,
6875                 &low_our_to_self_config, 0, &nodes[0].logger, 42)
6876         {
6877                 match error {
6878                         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()));  },
6879                         _ => panic!("Unexpected event"),
6880                 }
6881         } else { assert!(false); }
6882
6883         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6884         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6885         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()));
6886         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6887         accept_channel.to_self_delay = 200;
6888         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
6889         let reason_msg;
6890         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
6891                 match action {
6892                         &ErrorAction::SendErrorMessage { ref msg } => {
6893                                 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()));
6894                                 reason_msg = msg.data.clone();
6895                         },
6896                         _ => { panic!(); }
6897                 }
6898         } else { panic!(); }
6899         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
6900
6901         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
6902         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6903         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6904         open_channel.to_self_delay = 200;
6905         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6906                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), &open_channel, 0,
6907                 &high_their_to_self_config, 0, &nodes[0].logger, 42)
6908         {
6909                 match error {
6910                         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())); },
6911                         _ => panic!("Unexpected event"),
6912                 }
6913         } else { assert!(false); }
6914 }
6915
6916 #[test]
6917 fn test_check_htlc_underpaying() {
6918         // Send payment through A -> B but A is maliciously
6919         // sending a probe payment (i.e less than expected value0
6920         // to B, B should refuse payment.
6921
6922         let chanmon_cfgs = create_chanmon_cfgs(2);
6923         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6924         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6925         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6926
6927         // Create some initial channels
6928         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6929
6930         let scorer = test_utils::TestScorer::with_penalty(0);
6931         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
6932         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(channelmanager::provided_invoice_features());
6933         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();
6934         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
6935         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
6936         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6937         check_added_monitors!(nodes[0], 1);
6938
6939         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6940         assert_eq!(events.len(), 1);
6941         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
6942         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6943         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6944
6945         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
6946         // and then will wait a second random delay before failing the HTLC back:
6947         expect_pending_htlcs_forwardable!(nodes[1]);
6948         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
6949
6950         // Node 3 is expecting payment of 100_000 but received 10_000,
6951         // it should fail htlc like we didn't know the preimage.
6952         nodes[1].node.process_pending_htlc_forwards();
6953
6954         let events = nodes[1].node.get_and_clear_pending_msg_events();
6955         assert_eq!(events.len(), 1);
6956         let (update_fail_htlc, commitment_signed) = match events[0] {
6957                 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 } } => {
6958                         assert!(update_add_htlcs.is_empty());
6959                         assert!(update_fulfill_htlcs.is_empty());
6960                         assert_eq!(update_fail_htlcs.len(), 1);
6961                         assert!(update_fail_malformed_htlcs.is_empty());
6962                         assert!(update_fee.is_none());
6963                         (update_fail_htlcs[0].clone(), commitment_signed)
6964                 },
6965                 _ => panic!("Unexpected event"),
6966         };
6967         check_added_monitors!(nodes[1], 1);
6968
6969         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
6970         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
6971
6972         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
6973         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
6974         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
6975         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
6976 }
6977
6978 #[test]
6979 fn test_announce_disable_channels() {
6980         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
6981         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
6982
6983         let chanmon_cfgs = create_chanmon_cfgs(2);
6984         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6985         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6986         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6987
6988         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6989         create_announced_chan_between_nodes(&nodes, 1, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6990         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
6991
6992         // Disconnect peers
6993         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6994         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6995
6996         nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
6997         nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
6998         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
6999         assert_eq!(msg_events.len(), 3);
7000         let mut chans_disabled = HashMap::new();
7001         for e in msg_events {
7002                 match e {
7003                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7004                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7005                                 // Check that each channel gets updated exactly once
7006                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7007                                         panic!("Generated ChannelUpdate for wrong chan!");
7008                                 }
7009                         },
7010                         _ => panic!("Unexpected event"),
7011                 }
7012         }
7013         // Reconnect peers
7014         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7015         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7016         assert_eq!(reestablish_1.len(), 3);
7017         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
7018         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7019         assert_eq!(reestablish_2.len(), 3);
7020
7021         // Reestablish chan_1
7022         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7023         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7024         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7025         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7026         // Reestablish chan_2
7027         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
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[1]);
7030         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7031         // Reestablish chan_3
7032         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
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[2]);
7035         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7036
7037         nodes[0].node.timer_tick_occurred();
7038         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7039         nodes[0].node.timer_tick_occurred();
7040         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7041         assert_eq!(msg_events.len(), 3);
7042         for e in msg_events {
7043                 match e {
7044                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7045                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7046                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7047                                         // Each update should have a higher timestamp than the previous one, replacing
7048                                         // the old one.
7049                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7050                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7051                                 }
7052                         },
7053                         _ => panic!("Unexpected event"),
7054                 }
7055         }
7056         // Check that each channel gets updated exactly once
7057         assert!(chans_disabled.is_empty());
7058 }
7059
7060 #[test]
7061 fn test_bump_penalty_txn_on_revoked_commitment() {
7062         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7063         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7064
7065         let chanmon_cfgs = create_chanmon_cfgs(2);
7066         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7067         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7068         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7069
7070         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7071
7072         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7073         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id())
7074                 .with_features(channelmanager::provided_invoice_features());
7075         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7076         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7077
7078         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7079         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7080         assert_eq!(revoked_txn[0].output.len(), 4);
7081         assert_eq!(revoked_txn[0].input.len(), 1);
7082         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7083         let revoked_txid = revoked_txn[0].txid();
7084
7085         let mut penalty_sum = 0;
7086         for outp in revoked_txn[0].output.iter() {
7087                 if outp.script_pubkey.is_v0_p2wsh() {
7088                         penalty_sum += outp.value;
7089                 }
7090         }
7091
7092         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7093         let header_114 = connect_blocks(&nodes[1], 14);
7094
7095         // Actually revoke tx by claiming a HTLC
7096         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7097         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7098         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7099         check_added_monitors!(nodes[1], 1);
7100
7101         // One or more justice tx should have been broadcast, check it
7102         let penalty_1;
7103         let feerate_1;
7104         {
7105                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7106                 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7107                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7108                 assert_eq!(node_txn[0].output.len(), 1);
7109                 check_spends!(node_txn[0], revoked_txn[0]);
7110                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7111                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7112                 penalty_1 = node_txn[0].txid();
7113                 node_txn.clear();
7114         };
7115
7116         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7117         connect_blocks(&nodes[1], 15);
7118         let mut penalty_2 = penalty_1;
7119         let mut feerate_2 = 0;
7120         {
7121                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7122                 assert_eq!(node_txn.len(), 1);
7123                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7124                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7125                         assert_eq!(node_txn[0].output.len(), 1);
7126                         check_spends!(node_txn[0], revoked_txn[0]);
7127                         penalty_2 = node_txn[0].txid();
7128                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7129                         assert_ne!(penalty_2, penalty_1);
7130                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7131                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7132                         // Verify 25% bump heuristic
7133                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7134                         node_txn.clear();
7135                 }
7136         }
7137         assert_ne!(feerate_2, 0);
7138
7139         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7140         connect_blocks(&nodes[1], 1);
7141         let penalty_3;
7142         let mut feerate_3 = 0;
7143         {
7144                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7145                 assert_eq!(node_txn.len(), 1);
7146                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7147                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7148                         assert_eq!(node_txn[0].output.len(), 1);
7149                         check_spends!(node_txn[0], revoked_txn[0]);
7150                         penalty_3 = node_txn[0].txid();
7151                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7152                         assert_ne!(penalty_3, penalty_2);
7153                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7154                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7155                         // Verify 25% bump heuristic
7156                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7157                         node_txn.clear();
7158                 }
7159         }
7160         assert_ne!(feerate_3, 0);
7161
7162         nodes[1].node.get_and_clear_pending_events();
7163         nodes[1].node.get_and_clear_pending_msg_events();
7164 }
7165
7166 #[test]
7167 fn test_bump_penalty_txn_on_revoked_htlcs() {
7168         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7169         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7170
7171         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7172         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7173         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7174         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7175         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7176
7177         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7178         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7179         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(channelmanager::provided_invoice_features());
7180         let scorer = test_utils::TestScorer::with_penalty(0);
7181         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7182         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7183                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7184         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7185         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(channelmanager::provided_invoice_features());
7186         let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7187                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7188         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7189
7190         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7191         assert_eq!(revoked_local_txn[0].input.len(), 1);
7192         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7193
7194         // Revoke local commitment tx
7195         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7196
7197         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7198         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7199         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7200         check_closed_broadcast!(nodes[1], true);
7201         check_added_monitors!(nodes[1], 1);
7202         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7203         connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7204
7205         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
7206         assert_eq!(revoked_htlc_txn.len(), 3);
7207         check_spends!(revoked_htlc_txn[1], chan.3);
7208
7209         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7210         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7211         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7212
7213         assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7214         assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7215         assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7216         check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7217
7218         // Broadcast set of revoked txn on A
7219         let hash_128 = connect_blocks(&nodes[0], 40);
7220         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7221         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7222         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7223         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7224         let events = nodes[0].node.get_and_clear_pending_events();
7225         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7226         match events.last().unwrap() {
7227                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7228                 _ => panic!("Unexpected event"),
7229         }
7230         let first;
7231         let feerate_1;
7232         let penalty_txn;
7233         {
7234                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7235                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7236                 // Verify claim tx are spending revoked HTLC txn
7237
7238                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7239                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7240                 // which are included in the same block (they are broadcasted because we scan the
7241                 // transactions linearly and generate claims as we go, they likely should be removed in the
7242                 // future).
7243                 assert_eq!(node_txn[0].input.len(), 1);
7244                 check_spends!(node_txn[0], revoked_local_txn[0]);
7245                 assert_eq!(node_txn[1].input.len(), 1);
7246                 check_spends!(node_txn[1], revoked_local_txn[0]);
7247                 assert_eq!(node_txn[2].input.len(), 1);
7248                 check_spends!(node_txn[2], revoked_local_txn[0]);
7249
7250                 // Each of the three justice transactions claim a separate (single) output of the three
7251                 // available, which we check here:
7252                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7253                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7254                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7255
7256                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7257                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7258
7259                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7260                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7261                 // a remote commitment tx has already been confirmed).
7262                 check_spends!(node_txn[3], chan.3);
7263
7264                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7265                 // output, checked above).
7266                 assert_eq!(node_txn[4].input.len(), 2);
7267                 assert_eq!(node_txn[4].output.len(), 1);
7268                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7269
7270                 first = node_txn[4].txid();
7271                 // Store both feerates for later comparison
7272                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7273                 feerate_1 = fee_1 * 1000 / node_txn[4].weight() as u64;
7274                 penalty_txn = vec![node_txn[2].clone()];
7275                 node_txn.clear();
7276         }
7277
7278         // Connect one more block to see if bumped penalty are issued for HTLC txn
7279         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7280         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7281         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7282         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7283
7284         // Few more blocks to confirm penalty txn
7285         connect_blocks(&nodes[0], 4);
7286         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7287         let header_144 = connect_blocks(&nodes[0], 9);
7288         let node_txn = {
7289                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7290                 assert_eq!(node_txn.len(), 1);
7291
7292                 assert_eq!(node_txn[0].input.len(), 2);
7293                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7294                 // Verify bumped tx is different and 25% bump heuristic
7295                 assert_ne!(first, node_txn[0].txid());
7296                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7297                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7298                 assert!(feerate_2 * 100 > feerate_1 * 125);
7299                 let txn = vec![node_txn[0].clone()];
7300                 node_txn.clear();
7301                 txn
7302         };
7303         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7304         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7305         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7306         connect_blocks(&nodes[0], 20);
7307         {
7308                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7309                 // We verify than no new transaction has been broadcast because previously
7310                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7311                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7312                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7313                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7314                 // up bumped justice generation.
7315                 assert_eq!(node_txn.len(), 0);
7316                 node_txn.clear();
7317         }
7318         check_closed_broadcast!(nodes[0], true);
7319         check_added_monitors!(nodes[0], 1);
7320 }
7321
7322 #[test]
7323 fn test_bump_penalty_txn_on_remote_commitment() {
7324         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7325         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7326
7327         // Create 2 HTLCs
7328         // Provide preimage for one
7329         // Check aggregation
7330
7331         let chanmon_cfgs = create_chanmon_cfgs(2);
7332         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7333         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7334         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7335
7336         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7337         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7338         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7339
7340         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7341         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7342         assert_eq!(remote_txn[0].output.len(), 4);
7343         assert_eq!(remote_txn[0].input.len(), 1);
7344         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7345
7346         // Claim a HTLC without revocation (provide B monitor with preimage)
7347         nodes[1].node.claim_funds(payment_preimage);
7348         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7349         mine_transaction(&nodes[1], &remote_txn[0]);
7350         check_added_monitors!(nodes[1], 2);
7351         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7352
7353         // One or more claim tx should have been broadcast, check it
7354         let timeout;
7355         let preimage;
7356         let preimage_bump;
7357         let feerate_timeout;
7358         let feerate_preimage;
7359         {
7360                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7361                 // 5 transactions including:
7362                 //   local commitment + HTLC-Success
7363                 //   preimage and timeout sweeps from remote commitment + preimage sweep bump
7364                 assert_eq!(node_txn.len(), 5);
7365                 assert_eq!(node_txn[0].input.len(), 1);
7366                 assert_eq!(node_txn[3].input.len(), 1);
7367                 assert_eq!(node_txn[4].input.len(), 1);
7368                 check_spends!(node_txn[0], remote_txn[0]);
7369                 check_spends!(node_txn[3], remote_txn[0]);
7370                 check_spends!(node_txn[4], remote_txn[0]);
7371
7372                 check_spends!(node_txn[1], chan.3); // local commitment
7373                 check_spends!(node_txn[2], node_txn[1]); // local HTLC-Success
7374
7375                 preimage = node_txn[0].txid();
7376                 let index = node_txn[0].input[0].previous_output.vout;
7377                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7378                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7379
7380                 let (preimage_bump_tx, timeout_tx) = if node_txn[3].input[0].previous_output == node_txn[0].input[0].previous_output {
7381                         (node_txn[3].clone(), node_txn[4].clone())
7382                 } else {
7383                         (node_txn[4].clone(), node_txn[3].clone())
7384                 };
7385
7386                 preimage_bump = preimage_bump_tx;
7387                 check_spends!(preimage_bump, remote_txn[0]);
7388                 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7389
7390                 timeout = timeout_tx.txid();
7391                 let index = timeout_tx.input[0].previous_output.vout;
7392                 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7393                 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7394
7395                 node_txn.clear();
7396         };
7397         assert_ne!(feerate_timeout, 0);
7398         assert_ne!(feerate_preimage, 0);
7399
7400         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7401         connect_blocks(&nodes[1], 15);
7402         {
7403                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7404                 assert_eq!(node_txn.len(), 1);
7405                 assert_eq!(node_txn[0].input.len(), 1);
7406                 assert_eq!(preimage_bump.input.len(), 1);
7407                 check_spends!(node_txn[0], remote_txn[0]);
7408                 check_spends!(preimage_bump, remote_txn[0]);
7409
7410                 let index = preimage_bump.input[0].previous_output.vout;
7411                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7412                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7413                 assert!(new_feerate * 100 > feerate_timeout * 125);
7414                 assert_ne!(timeout, preimage_bump.txid());
7415
7416                 let index = node_txn[0].input[0].previous_output.vout;
7417                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7418                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7419                 assert!(new_feerate * 100 > feerate_preimage * 125);
7420                 assert_ne!(preimage, node_txn[0].txid());
7421
7422                 node_txn.clear();
7423         }
7424
7425         nodes[1].node.get_and_clear_pending_events();
7426         nodes[1].node.get_and_clear_pending_msg_events();
7427 }
7428
7429 #[test]
7430 fn test_counterparty_raa_skip_no_crash() {
7431         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7432         // commitment transaction, we would have happily carried on and provided them the next
7433         // commitment transaction based on one RAA forward. This would probably eventually have led to
7434         // channel closure, but it would not have resulted in funds loss. Still, our
7435         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7436         // check simply that the channel is closed in response to such an RAA, but don't check whether
7437         // we decide to punish our counterparty for revoking their funds (as we don't currently
7438         // implement that).
7439         let chanmon_cfgs = create_chanmon_cfgs(2);
7440         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7441         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7442         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7443         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
7444
7445         let per_commitment_secret;
7446         let next_per_commitment_point;
7447         {
7448                 let mut guard = nodes[0].node.channel_state.lock().unwrap();
7449                 let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
7450
7451                 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7452
7453                 // Make signer believe we got a counterparty signature, so that it allows the revocation
7454                 keys.get_enforcement_state().last_holder_commitment -= 1;
7455                 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7456
7457                 // Must revoke without gaps
7458                 keys.get_enforcement_state().last_holder_commitment -= 1;
7459                 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7460
7461                 keys.get_enforcement_state().last_holder_commitment -= 1;
7462                 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7463                         &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7464         }
7465
7466         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7467                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7468         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7469         check_added_monitors!(nodes[1], 1);
7470         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7471 }
7472
7473 #[test]
7474 fn test_bump_txn_sanitize_tracking_maps() {
7475         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7476         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7477
7478         let chanmon_cfgs = create_chanmon_cfgs(2);
7479         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7480         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7481         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7482
7483         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7484         // Lock HTLC in both directions
7485         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7486         let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7487
7488         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7489         assert_eq!(revoked_local_txn[0].input.len(), 1);
7490         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7491
7492         // Revoke local commitment tx
7493         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7494
7495         // Broadcast set of revoked txn on A
7496         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7497         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7498         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7499
7500         mine_transaction(&nodes[0], &revoked_local_txn[0]);
7501         check_closed_broadcast!(nodes[0], true);
7502         check_added_monitors!(nodes[0], 1);
7503         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7504         let penalty_txn = {
7505                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7506                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
7507                 check_spends!(node_txn[0], revoked_local_txn[0]);
7508                 check_spends!(node_txn[1], revoked_local_txn[0]);
7509                 check_spends!(node_txn[2], revoked_local_txn[0]);
7510                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7511                 node_txn.clear();
7512                 penalty_txn
7513         };
7514         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7515         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7516         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7517         {
7518                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7519                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7520                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7521         }
7522 }
7523
7524 #[test]
7525 fn test_pending_claimed_htlc_no_balance_underflow() {
7526         // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
7527         // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
7528         let chanmon_cfgs = create_chanmon_cfgs(2);
7529         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7530         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7531         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7532         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
7533
7534         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
7535         nodes[1].node.claim_funds(payment_preimage);
7536         expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
7537         check_added_monitors!(nodes[1], 1);
7538         let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7539
7540         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
7541         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
7542         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
7543         check_added_monitors!(nodes[0], 1);
7544         let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7545
7546         // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
7547         // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
7548         // can get our balance.
7549
7550         // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
7551         // the public key of the only hop. This works around ChannelDetails not showing the
7552         // almost-claimed HTLC as available balance.
7553         let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
7554         route.payment_params = None; // This is all wrong, but unnecessary
7555         route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
7556         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
7557         nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
7558
7559         assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
7560 }
7561
7562 #[test]
7563 fn test_channel_conf_timeout() {
7564         // Tests that, for inbound channels, we give up on them if the funding transaction does not
7565         // confirm within 2016 blocks, as recommended by BOLT 2.
7566         let chanmon_cfgs = create_chanmon_cfgs(2);
7567         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7568         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7569         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7570
7571         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());
7572
7573         // The outbound node should wait forever for confirmation:
7574         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7575         // copied here instead of directly referencing the constant.
7576         connect_blocks(&nodes[0], 2016);
7577         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7578
7579         // The inbound node should fail the channel after exactly 2016 blocks
7580         connect_blocks(&nodes[1], 2015);
7581         check_added_monitors!(nodes[1], 0);
7582         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7583
7584         connect_blocks(&nodes[1], 1);
7585         check_added_monitors!(nodes[1], 1);
7586         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
7587         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7588         assert_eq!(close_ev.len(), 1);
7589         match close_ev[0] {
7590                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7591                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7592                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7593                 },
7594                 _ => panic!("Unexpected event"),
7595         }
7596 }
7597
7598 #[test]
7599 fn test_override_channel_config() {
7600         let chanmon_cfgs = create_chanmon_cfgs(2);
7601         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7602         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7603         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7604
7605         // Node0 initiates a channel to node1 using the override config.
7606         let mut override_config = UserConfig::default();
7607         override_config.channel_handshake_config.our_to_self_delay = 200;
7608
7609         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7610
7611         // Assert the channel created by node0 is using the override config.
7612         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7613         assert_eq!(res.channel_flags, 0);
7614         assert_eq!(res.to_self_delay, 200);
7615 }
7616
7617 #[test]
7618 fn test_override_0msat_htlc_minimum() {
7619         let mut zero_config = UserConfig::default();
7620         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7621         let chanmon_cfgs = create_chanmon_cfgs(2);
7622         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7623         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7624         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7625
7626         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7627         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7628         assert_eq!(res.htlc_minimum_msat, 1);
7629
7630         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
7631         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7632         assert_eq!(res.htlc_minimum_msat, 1);
7633 }
7634
7635 #[test]
7636 fn test_channel_update_has_correct_htlc_maximum_msat() {
7637         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7638         // Bolt 7 specifies that if present `htlc_maximum_msat`:
7639         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7640         // 90% of the `channel_value`.
7641         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7642
7643         let mut config_30_percent = UserConfig::default();
7644         config_30_percent.channel_handshake_config.announced_channel = true;
7645         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7646         let mut config_50_percent = UserConfig::default();
7647         config_50_percent.channel_handshake_config.announced_channel = true;
7648         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7649         let mut config_95_percent = UserConfig::default();
7650         config_95_percent.channel_handshake_config.announced_channel = true;
7651         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7652         let mut config_100_percent = UserConfig::default();
7653         config_100_percent.channel_handshake_config.announced_channel = true;
7654         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7655
7656         let chanmon_cfgs = create_chanmon_cfgs(4);
7657         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7658         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)]);
7659         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7660
7661         let channel_value_satoshis = 100000;
7662         let channel_value_msat = channel_value_satoshis * 1000;
7663         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7664         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7665         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7666
7667         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());
7668         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());
7669
7670         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7671         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7672         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7673         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7674         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7675         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7676
7677         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7678         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7679         // `channel_value`.
7680         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7681         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7682         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7683         // `channel_value`.
7684         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7685 }
7686
7687 #[test]
7688 fn test_manually_accept_inbound_channel_request() {
7689         let mut manually_accept_conf = UserConfig::default();
7690         manually_accept_conf.manually_accept_inbound_channels = true;
7691         let chanmon_cfgs = create_chanmon_cfgs(2);
7692         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7693         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7694         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7695
7696         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7697         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7698
7699         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
7700
7701         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7702         // accepting the inbound channel request.
7703         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7704
7705         let events = nodes[1].node.get_and_clear_pending_events();
7706         match events[0] {
7707                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7708                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7709                 }
7710                 _ => panic!("Unexpected event"),
7711         }
7712
7713         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7714         assert_eq!(accept_msg_ev.len(), 1);
7715
7716         match accept_msg_ev[0] {
7717                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7718                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7719                 }
7720                 _ => panic!("Unexpected event"),
7721         }
7722
7723         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7724
7725         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7726         assert_eq!(close_msg_ev.len(), 1);
7727
7728         let events = nodes[1].node.get_and_clear_pending_events();
7729         match events[0] {
7730                 Event::ChannelClosed { user_channel_id, .. } => {
7731                         assert_eq!(user_channel_id, 23);
7732                 }
7733                 _ => panic!("Unexpected event"),
7734         }
7735 }
7736
7737 #[test]
7738 fn test_manually_reject_inbound_channel_request() {
7739         let mut manually_accept_conf = UserConfig::default();
7740         manually_accept_conf.manually_accept_inbound_channels = true;
7741         let chanmon_cfgs = create_chanmon_cfgs(2);
7742         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7743         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7744         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7745
7746         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7747         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7748
7749         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
7750
7751         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7752         // rejecting the inbound channel request.
7753         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7754
7755         let events = nodes[1].node.get_and_clear_pending_events();
7756         match events[0] {
7757                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7758                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7759                 }
7760                 _ => panic!("Unexpected event"),
7761         }
7762
7763         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7764         assert_eq!(close_msg_ev.len(), 1);
7765
7766         match close_msg_ev[0] {
7767                 MessageSendEvent::HandleError { ref node_id, .. } => {
7768                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7769                 }
7770                 _ => panic!("Unexpected event"),
7771         }
7772         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
7773 }
7774
7775 #[test]
7776 fn test_reject_funding_before_inbound_channel_accepted() {
7777         // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
7778         // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
7779         // the node operator before the counterparty sends a `FundingCreated` message. If a
7780         // `FundingCreated` message is received before the channel is accepted, it should be rejected
7781         // and the channel should be closed.
7782         let mut manually_accept_conf = UserConfig::default();
7783         manually_accept_conf.manually_accept_inbound_channels = true;
7784         let chanmon_cfgs = create_chanmon_cfgs(2);
7785         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7786         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7787         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7788
7789         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7790         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7791         let temp_channel_id = res.temporary_channel_id;
7792
7793         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
7794
7795         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
7796         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7797
7798         // Clear the `Event::OpenChannelRequest` event without responding to the request.
7799         nodes[1].node.get_and_clear_pending_events();
7800
7801         // Get the `AcceptChannel` message of `nodes[1]` without calling
7802         // `ChannelManager::accept_inbound_channel`, which generates a
7803         // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
7804         // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
7805         // succeed when `nodes[0]` is passed to it.
7806         let accept_chan_msg = {
7807                 let mut lock;
7808                 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
7809                 channel.get_accept_channel_message()
7810         };
7811         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_chan_msg);
7812
7813         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
7814
7815         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
7816         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
7817
7818         // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
7819         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
7820
7821         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7822         assert_eq!(close_msg_ev.len(), 1);
7823
7824         let expected_err = "FundingCreated message received before the channel was accepted";
7825         match close_msg_ev[0] {
7826                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
7827                         assert_eq!(msg.channel_id, temp_channel_id);
7828                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7829                         assert_eq!(msg.data, expected_err);
7830                 }
7831                 _ => panic!("Unexpected event"),
7832         }
7833
7834         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
7835 }
7836
7837 #[test]
7838 fn test_can_not_accept_inbound_channel_twice() {
7839         let mut manually_accept_conf = UserConfig::default();
7840         manually_accept_conf.manually_accept_inbound_channels = true;
7841         let chanmon_cfgs = create_chanmon_cfgs(2);
7842         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7843         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7844         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7845
7846         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7847         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7848
7849         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &res);
7850
7851         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7852         // accepting the inbound channel request.
7853         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7854
7855         let events = nodes[1].node.get_and_clear_pending_events();
7856         match events[0] {
7857                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7858                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7859                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7860                         match api_res {
7861                                 Err(APIError::APIMisuseError { err }) => {
7862                                         assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
7863                                 },
7864                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7865                                 Err(_) => panic!("Unexpected Error"),
7866                         }
7867                 }
7868                 _ => panic!("Unexpected event"),
7869         }
7870
7871         // Ensure that the channel wasn't closed after attempting to accept it twice.
7872         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7873         assert_eq!(accept_msg_ev.len(), 1);
7874
7875         match accept_msg_ev[0] {
7876                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7877                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7878                 }
7879                 _ => panic!("Unexpected event"),
7880         }
7881 }
7882
7883 #[test]
7884 fn test_can_not_accept_unknown_inbound_channel() {
7885         let chanmon_cfg = create_chanmon_cfgs(2);
7886         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
7887         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
7888         let nodes = create_network(2, &node_cfg, &node_chanmgr);
7889
7890         let unknown_channel_id = [0; 32];
7891         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
7892         match api_res {
7893                 Err(APIError::ChannelUnavailable { err }) => {
7894                         assert_eq!(err, "Can't accept a channel that doesn't exist");
7895                 },
7896                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
7897                 Err(_) => panic!("Unexpected Error"),
7898         }
7899 }
7900
7901 #[test]
7902 fn test_simple_mpp() {
7903         // Simple test of sending a multi-path payment.
7904         let chanmon_cfgs = create_chanmon_cfgs(4);
7905         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7906         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
7907         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7908
7909         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;
7910         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;
7911         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;
7912         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;
7913
7914         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
7915         let path = route.paths[0].clone();
7916         route.paths.push(path);
7917         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
7918         route.paths[0][0].short_channel_id = chan_1_id;
7919         route.paths[0][1].short_channel_id = chan_3_id;
7920         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
7921         route.paths[1][0].short_channel_id = chan_2_id;
7922         route.paths[1][1].short_channel_id = chan_4_id;
7923         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
7924         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
7925 }
7926
7927 #[test]
7928 fn test_preimage_storage() {
7929         // Simple test of payment preimage storage allowing no client-side storage to claim payments
7930         let chanmon_cfgs = create_chanmon_cfgs(2);
7931         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7932         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7933         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7934
7935         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
7936
7937         {
7938                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
7939                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
7940                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
7941                 check_added_monitors!(nodes[0], 1);
7942                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7943                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7944                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7945                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7946         }
7947         // Note that after leaving the above scope we have no knowledge of any arguments or return
7948         // values from previous calls.
7949         expect_pending_htlcs_forwardable!(nodes[1]);
7950         let events = nodes[1].node.get_and_clear_pending_events();
7951         assert_eq!(events.len(), 1);
7952         match events[0] {
7953                 Event::PaymentReceived { ref purpose, .. } => {
7954                         match &purpose {
7955                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
7956                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
7957                                 },
7958                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
7959                         }
7960                 },
7961                 _ => panic!("Unexpected event"),
7962         }
7963 }
7964
7965 #[test]
7966 #[allow(deprecated)]
7967 fn test_secret_timeout() {
7968         // Simple test of payment secret storage time outs. After
7969         // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
7970         let chanmon_cfgs = create_chanmon_cfgs(2);
7971         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7972         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7973         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7974
7975         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
7976
7977         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
7978
7979         // We should fail to register the same payment hash twice, at least until we've connected a
7980         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
7981         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
7982                 assert_eq!(err, "Duplicate payment hash");
7983         } else { panic!(); }
7984         let mut block = {
7985                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
7986                 Block {
7987                         header: BlockHeader {
7988                                 version: 0x2000000,
7989                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
7990                                 merkle_root: TxMerkleNode::all_zeros(),
7991                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
7992                         txdata: vec![],
7993                 }
7994         };
7995         connect_block(&nodes[1], &block);
7996         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
7997                 assert_eq!(err, "Duplicate payment hash");
7998         } else { panic!(); }
7999
8000         // If we then connect the second block, we should be able to register the same payment hash
8001         // again (this time getting a new payment secret).
8002         block.header.prev_blockhash = block.header.block_hash();
8003         block.header.time += 1;
8004         connect_block(&nodes[1], &block);
8005         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8006         assert_ne!(payment_secret_1, our_payment_secret);
8007
8008         {
8009                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8010                 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret), PaymentId(payment_hash.0)).unwrap();
8011                 check_added_monitors!(nodes[0], 1);
8012                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8013                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8014                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8015                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8016         }
8017         // Note that after leaving the above scope we have no knowledge of any arguments or return
8018         // values from previous calls.
8019         expect_pending_htlcs_forwardable!(nodes[1]);
8020         let events = nodes[1].node.get_and_clear_pending_events();
8021         assert_eq!(events.len(), 1);
8022         match events[0] {
8023                 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8024                         assert!(payment_preimage.is_none());
8025                         assert_eq!(payment_secret, our_payment_secret);
8026                         // We don't actually have the payment preimage with which to claim this payment!
8027                 },
8028                 _ => panic!("Unexpected event"),
8029         }
8030 }
8031
8032 #[test]
8033 fn test_bad_secret_hash() {
8034         // Simple test of unregistered payment hash/invalid payment secret handling
8035         let chanmon_cfgs = create_chanmon_cfgs(2);
8036         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8037         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8038         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8039
8040         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
8041
8042         let random_payment_hash = PaymentHash([42; 32]);
8043         let random_payment_secret = PaymentSecret([43; 32]);
8044         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8045         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8046
8047         // All the below cases should end up being handled exactly identically, so we macro the
8048         // resulting events.
8049         macro_rules! handle_unknown_invalid_payment_data {
8050                 ($payment_hash: expr) => {
8051                         check_added_monitors!(nodes[0], 1);
8052                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8053                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8054                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8055                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8056
8057                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8058                         // again to process the pending backwards-failure of the HTLC
8059                         expect_pending_htlcs_forwardable!(nodes[1]);
8060                         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8061                         check_added_monitors!(nodes[1], 1);
8062
8063                         // We should fail the payment back
8064                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8065                         match events.pop().unwrap() {
8066                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8067                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8068                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8069                                 },
8070                                 _ => panic!("Unexpected event"),
8071                         }
8072                 }
8073         }
8074
8075         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8076         // Error data is the HTLC value (100,000) and current block height
8077         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8078
8079         // Send a payment with the right payment hash but the wrong payment secret
8080         nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8081         handle_unknown_invalid_payment_data!(our_payment_hash);
8082         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8083
8084         // Send a payment with a random payment hash, but the right payment secret
8085         nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8086         handle_unknown_invalid_payment_data!(random_payment_hash);
8087         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8088
8089         // Send a payment with a random payment hash and random payment secret
8090         nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_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
8095 #[test]
8096 fn test_update_err_monitor_lockdown() {
8097         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8098         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8099         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8100         // error.
8101         //
8102         // This scenario may happen in a watchtower setup, where watchtower process a block height
8103         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8104         // commitment at same time.
8105
8106         let chanmon_cfgs = create_chanmon_cfgs(2);
8107         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8108         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8109         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8110
8111         // Create some initial channel
8112         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8113         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8114
8115         // Rebalance the network to generate htlc in the two directions
8116         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8117
8118         // Route a HTLC from node 0 to node 1 (but don't settle)
8119         let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8120
8121         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8122         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8123         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8124         let persister = test_utils::TestPersister::new();
8125         let watchtower = {
8126                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8127                 let mut w = test_utils::TestVecWriter(Vec::new());
8128                 monitor.write(&mut w).unwrap();
8129                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8130                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8131                 assert!(new_monitor == *monitor);
8132                 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);
8133                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8134                 watchtower
8135         };
8136         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8137         let block = Block { header, txdata: vec![] };
8138         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8139         // transaction lock time requirements here.
8140         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8141         watchtower.chain_monitor.block_connected(&block, 200);
8142
8143         // Try to update ChannelMonitor
8144         nodes[1].node.claim_funds(preimage);
8145         check_added_monitors!(nodes[1], 1);
8146         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8147
8148         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8149         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8150         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8151         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8152                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8153                         assert_eq!(watchtower.chain_monitor.update_channel(outpoint, update.clone()), ChannelMonitorUpdateStatus::PermanentFailure);
8154                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, update), ChannelMonitorUpdateStatus::Completed);
8155                 } else { assert!(false); }
8156         } else { assert!(false); };
8157         // Our local monitor is in-sync and hasn't processed yet timeout
8158         check_added_monitors!(nodes[0], 1);
8159         let events = nodes[0].node.get_and_clear_pending_events();
8160         assert_eq!(events.len(), 1);
8161 }
8162
8163 #[test]
8164 fn test_concurrent_monitor_claim() {
8165         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8166         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8167         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8168         // state N+1 confirms. Alice claims output from state N+1.
8169
8170         let chanmon_cfgs = create_chanmon_cfgs(2);
8171         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8172         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8173         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8174
8175         // Create some initial channel
8176         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8177         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8178
8179         // Rebalance the network to generate htlc in the two directions
8180         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8181
8182         // Route a HTLC from node 0 to node 1 (but don't settle)
8183         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8184
8185         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8186         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8187         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8188         let persister = test_utils::TestPersister::new();
8189         let watchtower_alice = {
8190                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8191                 let mut w = test_utils::TestVecWriter(Vec::new());
8192                 monitor.write(&mut w).unwrap();
8193                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8194                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8195                 assert!(new_monitor == *monitor);
8196                 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);
8197                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8198                 watchtower
8199         };
8200         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8201         let block = Block { header, txdata: vec![] };
8202         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8203         // transaction lock time requirements here.
8204         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));
8205         watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8206
8207         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8208         {
8209                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8210                 assert_eq!(txn.len(), 2);
8211                 txn.clear();
8212         }
8213
8214         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8215         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8216         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8217         let persister = test_utils::TestPersister::new();
8218         let watchtower_bob = {
8219                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8220                 let mut w = test_utils::TestVecWriter(Vec::new());
8221                 monitor.write(&mut w).unwrap();
8222                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8223                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8224                 assert!(new_monitor == *monitor);
8225                 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);
8226                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8227                 watchtower
8228         };
8229         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8230         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8231
8232         // Route another payment to generate another update with still previous HTLC pending
8233         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8234         {
8235                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
8236         }
8237         check_added_monitors!(nodes[1], 1);
8238
8239         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8240         assert_eq!(updates.update_add_htlcs.len(), 1);
8241         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8242         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8243                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8244                         // Watchtower Alice should already have seen the block and reject the update
8245                         assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()), ChannelMonitorUpdateStatus::PermanentFailure);
8246                         assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()), ChannelMonitorUpdateStatus::Completed);
8247                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, update), ChannelMonitorUpdateStatus::Completed);
8248                 } else { assert!(false); }
8249         } else { assert!(false); };
8250         // Our local monitor is in-sync and hasn't processed yet timeout
8251         check_added_monitors!(nodes[0], 1);
8252
8253         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8254         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8255         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8256
8257         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8258         let bob_state_y;
8259         {
8260                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8261                 assert_eq!(txn.len(), 2);
8262                 bob_state_y = txn[0].clone();
8263                 txn.clear();
8264         };
8265
8266         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8267         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8268         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);
8269         {
8270                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8271                 assert_eq!(htlc_txn.len(), 1);
8272                 check_spends!(htlc_txn[0], bob_state_y);
8273         }
8274 }
8275
8276 #[test]
8277 fn test_pre_lockin_no_chan_closed_update() {
8278         // Test that if a peer closes a channel in response to a funding_created message we don't
8279         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8280         // message).
8281         //
8282         // Doing so would imply a channel monitor update before the initial channel monitor
8283         // registration, violating our API guarantees.
8284         //
8285         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8286         // then opening a second channel with the same funding output as the first (which is not
8287         // rejected because the first channel does not exist in the ChannelManager) and closing it
8288         // before receiving funding_signed.
8289         let chanmon_cfgs = create_chanmon_cfgs(2);
8290         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8291         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8292         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8293
8294         // Create an initial channel
8295         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8296         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8297         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
8298         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8299         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_chan_msg);
8300
8301         // Move the first channel through the funding flow...
8302         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8303
8304         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8305         check_added_monitors!(nodes[0], 0);
8306
8307         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8308         let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8309         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8310         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8311         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8312 }
8313
8314 #[test]
8315 fn test_htlc_no_detection() {
8316         // This test is a mutation to underscore the detection logic bug we had
8317         // before #653. HTLC value routed is above the remaining balance, thus
8318         // inverting HTLC and `to_remote` output. HTLC will come second and
8319         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8320         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8321         // outputs order detection for correct spending children filtring.
8322
8323         let chanmon_cfgs = create_chanmon_cfgs(2);
8324         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8325         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8326         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8327
8328         // Create some initial channels
8329         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8330
8331         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8332         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8333         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8334         assert_eq!(local_txn[0].input.len(), 1);
8335         assert_eq!(local_txn[0].output.len(), 3);
8336         check_spends!(local_txn[0], chan_1.3);
8337
8338         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8339         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8340         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8341         // We deliberately connect the local tx twice as this should provoke a failure calling
8342         // this test before #653 fix.
8343         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);
8344         check_closed_broadcast!(nodes[0], true);
8345         check_added_monitors!(nodes[0], 1);
8346         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8347         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8348
8349         let htlc_timeout = {
8350                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8351                 assert_eq!(node_txn[1].input.len(), 1);
8352                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8353                 check_spends!(node_txn[1], local_txn[0]);
8354                 node_txn[1].clone()
8355         };
8356
8357         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8358         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8359         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8360         expect_payment_failed!(nodes[0], our_payment_hash, false);
8361 }
8362
8363 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8364         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8365         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8366         // Carol, Alice would be the upstream node, and Carol the downstream.)
8367         //
8368         // Steps of the test:
8369         // 1) Alice sends a HTLC to Carol through Bob.
8370         // 2) Carol doesn't settle the HTLC.
8371         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8372         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8373         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8374         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8375         // 5) Carol release the preimage to Bob off-chain.
8376         // 6) Bob claims the offered output on the broadcasted commitment.
8377         let chanmon_cfgs = create_chanmon_cfgs(3);
8378         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8379         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8380         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8381
8382         // Create some initial channels
8383         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8384         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8385
8386         // Steps (1) and (2):
8387         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8388         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8389
8390         // Check that Alice's commitment transaction now contains an output for this HTLC.
8391         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8392         check_spends!(alice_txn[0], chan_ab.3);
8393         assert_eq!(alice_txn[0].output.len(), 2);
8394         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8395         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8396         assert_eq!(alice_txn.len(), 2);
8397
8398         // Steps (3) and (4):
8399         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8400         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8401         let mut force_closing_node = 0; // Alice force-closes
8402         let mut counterparty_node = 1; // Bob if Alice force-closes
8403
8404         // Bob force-closes
8405         if !broadcast_alice {
8406                 force_closing_node = 1;
8407                 counterparty_node = 0;
8408         }
8409         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8410         check_closed_broadcast!(nodes[force_closing_node], true);
8411         check_added_monitors!(nodes[force_closing_node], 1);
8412         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8413         if go_onchain_before_fulfill {
8414                 let txn_to_broadcast = match broadcast_alice {
8415                         true => alice_txn.clone(),
8416                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8417                 };
8418                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8419                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8420                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8421                 if broadcast_alice {
8422                         check_closed_broadcast!(nodes[1], true);
8423                         check_added_monitors!(nodes[1], 1);
8424                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8425                 }
8426                 assert_eq!(bob_txn.len(), 1);
8427                 check_spends!(bob_txn[0], chan_ab.3);
8428         }
8429
8430         // Step (5):
8431         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8432         // process of removing the HTLC from their commitment transactions.
8433         nodes[2].node.claim_funds(payment_preimage);
8434         check_added_monitors!(nodes[2], 1);
8435         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8436
8437         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8438         assert!(carol_updates.update_add_htlcs.is_empty());
8439         assert!(carol_updates.update_fail_htlcs.is_empty());
8440         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8441         assert!(carol_updates.update_fee.is_none());
8442         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8443
8444         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8445         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8446         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8447         if !go_onchain_before_fulfill && broadcast_alice {
8448                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8449                 assert_eq!(events.len(), 1);
8450                 match events[0] {
8451                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8452                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8453                         },
8454                         _ => panic!("Unexpected event"),
8455                 };
8456         }
8457         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8458         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8459         // Carol<->Bob's updated commitment transaction info.
8460         check_added_monitors!(nodes[1], 2);
8461
8462         let events = nodes[1].node.get_and_clear_pending_msg_events();
8463         assert_eq!(events.len(), 2);
8464         let bob_revocation = match events[0] {
8465                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8466                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8467                         (*msg).clone()
8468                 },
8469                 _ => panic!("Unexpected event"),
8470         };
8471         let bob_updates = match events[1] {
8472                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8473                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8474                         (*updates).clone()
8475                 },
8476                 _ => panic!("Unexpected event"),
8477         };
8478
8479         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8480         check_added_monitors!(nodes[2], 1);
8481         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8482         check_added_monitors!(nodes[2], 1);
8483
8484         let events = nodes[2].node.get_and_clear_pending_msg_events();
8485         assert_eq!(events.len(), 1);
8486         let carol_revocation = match events[0] {
8487                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8488                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8489                         (*msg).clone()
8490                 },
8491                 _ => panic!("Unexpected event"),
8492         };
8493         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8494         check_added_monitors!(nodes[1], 1);
8495
8496         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8497         // here's where we put said channel's commitment tx on-chain.
8498         let mut txn_to_broadcast = alice_txn.clone();
8499         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8500         if !go_onchain_before_fulfill {
8501                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8502                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8503                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8504                 if broadcast_alice {
8505                         check_closed_broadcast!(nodes[1], true);
8506                         check_added_monitors!(nodes[1], 1);
8507                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8508                 }
8509                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8510                 if broadcast_alice {
8511                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8512                         // new block being connected. The ChannelManager being notified triggers a monitor update,
8513                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8514                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8515                         // broadcasted.
8516                         assert_eq!(bob_txn.len(), 3);
8517                         check_spends!(bob_txn[1], chan_ab.3);
8518                 } else {
8519                         assert_eq!(bob_txn.len(), 2);
8520                         check_spends!(bob_txn[0], chan_ab.3);
8521                 }
8522         }
8523
8524         // Step (6):
8525         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8526         // broadcasted commitment transaction.
8527         {
8528                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8529                 if go_onchain_before_fulfill {
8530                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8531                         assert_eq!(bob_txn.len(), 2);
8532                 }
8533                 let script_weight = match broadcast_alice {
8534                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8535                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8536                 };
8537                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8538                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8539                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8540                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8541                 if broadcast_alice && !go_onchain_before_fulfill {
8542                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8543                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8544                 } else {
8545                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8546                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8547                 }
8548         }
8549 }
8550
8551 #[test]
8552 fn test_onchain_htlc_settlement_after_close() {
8553         do_test_onchain_htlc_settlement_after_close(true, true);
8554         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8555         do_test_onchain_htlc_settlement_after_close(true, false);
8556         do_test_onchain_htlc_settlement_after_close(false, false);
8557 }
8558
8559 #[test]
8560 fn test_duplicate_chan_id() {
8561         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8562         // already open we reject it and keep the old channel.
8563         //
8564         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8565         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8566         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8567         // updating logic for the existing channel.
8568         let chanmon_cfgs = create_chanmon_cfgs(2);
8569         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8570         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8571         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8572
8573         // Create an initial channel
8574         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8575         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8576         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
8577         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()));
8578
8579         // Try to create a second channel with the same temporary_channel_id as the first and check
8580         // that it is rejected.
8581         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
8582         {
8583                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8584                 assert_eq!(events.len(), 1);
8585                 match events[0] {
8586                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8587                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8588                                 // first (valid) and second (invalid) channels are closed, given they both have
8589                                 // the same non-temporary channel_id. However, currently we do not, so we just
8590                                 // move forward with it.
8591                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8592                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8593                         },
8594                         _ => panic!("Unexpected event"),
8595                 }
8596         }
8597
8598         // Move the first channel through the funding flow...
8599         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8600
8601         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8602         check_added_monitors!(nodes[0], 0);
8603
8604         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8605         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8606         {
8607                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8608                 assert_eq!(added_monitors.len(), 1);
8609                 assert_eq!(added_monitors[0].0, funding_output);
8610                 added_monitors.clear();
8611         }
8612         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8613
8614         let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8615         let channel_id = funding_outpoint.to_channel_id();
8616
8617         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8618         // temporary one).
8619
8620         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8621         // Technically this is allowed by the spec, but we don't support it and there's little reason
8622         // to. Still, it shouldn't cause any other issues.
8623         open_chan_msg.temporary_channel_id = channel_id;
8624         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_msg);
8625         {
8626                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8627                 assert_eq!(events.len(), 1);
8628                 match events[0] {
8629                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8630                                 // Technically, at this point, nodes[1] would be justified in thinking both
8631                                 // channels are closed, but currently we do not, so we just move forward with it.
8632                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8633                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8634                         },
8635                         _ => panic!("Unexpected event"),
8636                 }
8637         }
8638
8639         // Now try to create a second channel which has a duplicate funding output.
8640         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8641         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8642         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_chan_2_msg);
8643         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()));
8644         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8645
8646         let funding_created = {
8647                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8648                 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
8649                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8650                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8651                 // channelmanager in a possibly nonsense state instead).
8652                 let mut as_chan = a_channel_lock.by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8653                 let logger = test_utils::TestLogger::new();
8654                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8655         };
8656         check_added_monitors!(nodes[0], 0);
8657         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8658         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8659         // still needs to be cleared here.
8660         check_added_monitors!(nodes[1], 1);
8661
8662         // ...still, nodes[1] will reject the duplicate channel.
8663         {
8664                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8665                 assert_eq!(events.len(), 1);
8666                 match events[0] {
8667                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8668                                 // Technically, at this point, nodes[1] would be justified in thinking both
8669                                 // channels are closed, but currently we do not, so we just move forward with it.
8670                                 assert_eq!(msg.channel_id, channel_id);
8671                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8672                         },
8673                         _ => panic!("Unexpected event"),
8674                 }
8675         }
8676
8677         // finally, finish creating the original channel and send a payment over it to make sure
8678         // everything is functional.
8679         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8680         {
8681                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8682                 assert_eq!(added_monitors.len(), 1);
8683                 assert_eq!(added_monitors[0].0, funding_output);
8684                 added_monitors.clear();
8685         }
8686
8687         let events_4 = nodes[0].node.get_and_clear_pending_events();
8688         assert_eq!(events_4.len(), 0);
8689         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8690         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8691
8692         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8693         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
8694         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8695
8696         send_payment(&nodes[0], &[&nodes[1]], 8000000);
8697 }
8698
8699 #[test]
8700 fn test_error_chans_closed() {
8701         // Test that we properly handle error messages, closing appropriate channels.
8702         //
8703         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8704         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8705         // we can test various edge cases around it to ensure we don't regress.
8706         let chanmon_cfgs = create_chanmon_cfgs(3);
8707         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8708         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8709         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8710
8711         // Create some initial channels
8712         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8713         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8714         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8715
8716         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8717         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8718         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8719
8720         // Closing a channel from a different peer has no effect
8721         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8722         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8723
8724         // Closing one channel doesn't impact others
8725         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8726         check_added_monitors!(nodes[0], 1);
8727         check_closed_broadcast!(nodes[0], false);
8728         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
8729         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8730         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8731         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);
8732         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);
8733
8734         // A null channel ID should close all channels
8735         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8736         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8737         check_added_monitors!(nodes[0], 2);
8738         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
8739         let events = nodes[0].node.get_and_clear_pending_msg_events();
8740         assert_eq!(events.len(), 2);
8741         match events[0] {
8742                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8743                         assert_eq!(msg.contents.flags & 2, 2);
8744                 },
8745                 _ => panic!("Unexpected event"),
8746         }
8747         match events[1] {
8748                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8749                         assert_eq!(msg.contents.flags & 2, 2);
8750                 },
8751                 _ => panic!("Unexpected event"),
8752         }
8753         // Note that at this point users of a standard PeerHandler will end up calling
8754         // peer_disconnected with no_connection_possible set to false, duplicating the
8755         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
8756         // users with their own peer handling logic. We duplicate the call here, however.
8757         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8758         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8759
8760         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
8761         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8762         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8763 }
8764
8765 #[test]
8766 fn test_invalid_funding_tx() {
8767         // Test that we properly handle invalid funding transactions sent to us from a peer.
8768         //
8769         // Previously, all other major lightning implementations had failed to properly sanitize
8770         // funding transactions from their counterparties, leading to a multi-implementation critical
8771         // security vulnerability (though we always sanitized properly, we've previously had
8772         // un-released crashes in the sanitization process).
8773         //
8774         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
8775         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
8776         // gave up on it. We test this here by generating such a transaction.
8777         let chanmon_cfgs = create_chanmon_cfgs(2);
8778         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8779         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8780         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8781
8782         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
8783         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()));
8784         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()));
8785
8786         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
8787
8788         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
8789         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
8790         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
8791         // its length.
8792         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
8793         let wit_program_script: Script = wit_program.into();
8794         for output in tx.output.iter_mut() {
8795                 // Make the confirmed funding transaction have a bogus script_pubkey
8796                 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
8797         }
8798
8799         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
8800         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()));
8801         check_added_monitors!(nodes[1], 1);
8802
8803         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()));
8804         check_added_monitors!(nodes[0], 1);
8805
8806         let events_1 = nodes[0].node.get_and_clear_pending_events();
8807         assert_eq!(events_1.len(), 0);
8808
8809         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8810         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8811         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
8812
8813         let expected_err = "funding tx had wrong script/value or output index";
8814         confirm_transaction_at(&nodes[1], &tx, 1);
8815         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8816         check_added_monitors!(nodes[1], 1);
8817         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
8818         assert_eq!(events_2.len(), 1);
8819         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
8820                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8821                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
8822                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
8823                 } else { panic!(); }
8824         } else { panic!(); }
8825         assert_eq!(nodes[1].node.list_channels().len(), 0);
8826
8827         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
8828         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
8829         // as its not 32 bytes long.
8830         let mut spend_tx = Transaction {
8831                 version: 2i32, lock_time: PackedLockTime::ZERO,
8832                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
8833                         previous_output: BitcoinOutPoint {
8834                                 txid: tx.txid(),
8835                                 vout: idx as u32,
8836                         },
8837                         script_sig: Script::new(),
8838                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
8839                         witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
8840                 }).collect(),
8841                 output: vec![TxOut {
8842                         value: 1000,
8843                         script_pubkey: Script::new(),
8844                 }]
8845         };
8846         check_spends!(spend_tx, tx);
8847         mine_transaction(&nodes[1], &spend_tx);
8848 }
8849
8850 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
8851         // In the first version of the chain::Confirm interface, after a refactor was made to not
8852         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
8853         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
8854         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
8855         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
8856         // spending transaction until height N+1 (or greater). This was due to the way
8857         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
8858         // spending transaction at the height the input transaction was confirmed at, not whether we
8859         // should broadcast a spending transaction at the current height.
8860         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
8861         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
8862         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
8863         // until we learned about an additional block.
8864         //
8865         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
8866         // aren't broadcasting transactions too early (ie not broadcasting them at all).
8867         let chanmon_cfgs = create_chanmon_cfgs(3);
8868         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8869         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8870         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8871         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
8872
8873         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8874         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8875         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
8876         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
8877         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8878
8879         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
8880         check_closed_broadcast!(nodes[1], true);
8881         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8882         check_added_monitors!(nodes[1], 1);
8883         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
8884         assert_eq!(node_txn.len(), 1);
8885
8886         let conf_height = nodes[1].best_block_info().1;
8887         if !test_height_before_timelock {
8888                 connect_blocks(&nodes[1], 24 * 6);
8889         }
8890         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
8891                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
8892         if test_height_before_timelock {
8893                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
8894                 // generate any events or broadcast any transactions
8895                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
8896                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
8897         } else {
8898                 // We should broadcast an HTLC transaction spending our funding transaction first
8899                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
8900                 assert_eq!(spending_txn.len(), 2);
8901                 assert_eq!(spending_txn[0], node_txn[0]);
8902                 check_spends!(spending_txn[1], node_txn[0]);
8903                 // We should also generate a SpendableOutputs event with the to_self output (as its
8904                 // timelock is up).
8905                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
8906                 assert_eq!(descriptor_spend_txn.len(), 1);
8907
8908                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
8909                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
8910                 // additional block built on top of the current chain.
8911                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
8912                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
8913                 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 }]);
8914                 check_added_monitors!(nodes[1], 1);
8915
8916                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8917                 assert!(updates.update_add_htlcs.is_empty());
8918                 assert!(updates.update_fulfill_htlcs.is_empty());
8919                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8920                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8921                 assert!(updates.update_fee.is_none());
8922                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
8923                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
8924                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
8925         }
8926 }
8927
8928 #[test]
8929 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
8930         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
8931         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
8932 }
8933
8934 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
8935         let chanmon_cfgs = create_chanmon_cfgs(2);
8936         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8937         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8938         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8939
8940         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
8941
8942         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
8943                 .with_features(channelmanager::provided_invoice_features());
8944         let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
8945
8946         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
8947
8948         {
8949                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8950                 check_added_monitors!(nodes[0], 1);
8951                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8952                 assert_eq!(events.len(), 1);
8953                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8954                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8955                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8956         }
8957         expect_pending_htlcs_forwardable!(nodes[1]);
8958         expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
8959
8960         {
8961                 // Note that we use a different PaymentId here to allow us to duplicativly pay
8962                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
8963                 check_added_monitors!(nodes[0], 1);
8964                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8965                 assert_eq!(events.len(), 1);
8966                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8967                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8968                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8969                 // At this point, nodes[1] would notice it has too much value for the payment. It will
8970                 // assume the second is a privacy attack (no longer particularly relevant
8971                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
8972                 // the first HTLC delivered above.
8973         }
8974
8975         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
8976         nodes[1].node.process_pending_htlc_forwards();
8977
8978         if test_for_second_fail_panic {
8979                 // Now we go fail back the first HTLC from the user end.
8980                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
8981
8982                 let expected_destinations = vec![
8983                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
8984                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
8985                 ];
8986                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],  expected_destinations);
8987                 nodes[1].node.process_pending_htlc_forwards();
8988
8989                 check_added_monitors!(nodes[1], 1);
8990                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8991                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
8992
8993                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
8994                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
8995                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
8996
8997                 let failure_events = nodes[0].node.get_and_clear_pending_events();
8998                 assert_eq!(failure_events.len(), 2);
8999                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9000                 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9001         } else {
9002                 // Let the second HTLC fail and claim the first
9003                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9004                 nodes[1].node.process_pending_htlc_forwards();
9005
9006                 check_added_monitors!(nodes[1], 1);
9007                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9008                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9009                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9010
9011                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9012
9013                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9014         }
9015 }
9016
9017 #[test]
9018 fn test_dup_htlc_second_fail_panic() {
9019         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9020         // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
9021         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9022         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9023         do_test_dup_htlc_second_rejected(true);
9024 }
9025
9026 #[test]
9027 fn test_dup_htlc_second_rejected() {
9028         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9029         // simply reject the second HTLC but are still able to claim the first HTLC.
9030         do_test_dup_htlc_second_rejected(false);
9031 }
9032
9033 #[test]
9034 fn test_inconsistent_mpp_params() {
9035         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9036         // such HTLC and allow the second to stay.
9037         let chanmon_cfgs = create_chanmon_cfgs(4);
9038         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9039         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9040         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9041
9042         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9043         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9044         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9045         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());
9046
9047         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
9048                 .with_features(channelmanager::provided_invoice_features());
9049         let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9050         assert_eq!(route.paths.len(), 2);
9051         route.paths.sort_by(|path_a, _| {
9052                 // Sort the path so that the path through nodes[1] comes first
9053                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9054                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9055         });
9056         let payment_params_opt = Some(payment_params);
9057
9058         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9059
9060         let cur_height = nodes[0].best_block_info().1;
9061         let payment_id = PaymentId([42; 32]);
9062
9063         let session_privs = {
9064                 // We create a fake route here so that we start with three pending HTLCs, which we'll
9065                 // ultimately have, just not right away.
9066                 let mut dup_route = route.clone();
9067                 dup_route.paths.push(route.paths[1].clone());
9068                 nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(our_payment_secret), payment_id, &dup_route).unwrap()
9069         };
9070         {
9071                 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();
9072                 check_added_monitors!(nodes[0], 1);
9073
9074                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9075                 assert_eq!(events.len(), 1);
9076                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9077         }
9078         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9079
9080         {
9081                 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();
9082                 check_added_monitors!(nodes[0], 1);
9083
9084                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9085                 assert_eq!(events.len(), 1);
9086                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9087
9088                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9089                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9090
9091                 expect_pending_htlcs_forwardable!(nodes[2]);
9092                 check_added_monitors!(nodes[2], 1);
9093
9094                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9095                 assert_eq!(events.len(), 1);
9096                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9097
9098                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9099                 check_added_monitors!(nodes[3], 0);
9100                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9101
9102                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9103                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9104                 // post-payment_secrets) and fail back the new HTLC.
9105         }
9106         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9107         nodes[3].node.process_pending_htlc_forwards();
9108         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9109         nodes[3].node.process_pending_htlc_forwards();
9110
9111         check_added_monitors!(nodes[3], 1);
9112
9113         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9114         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9115         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9116
9117         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 }]);
9118         check_added_monitors!(nodes[2], 1);
9119
9120         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9121         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9122         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9123
9124         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9125
9126         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();
9127         check_added_monitors!(nodes[0], 1);
9128
9129         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9130         assert_eq!(events.len(), 1);
9131         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9132
9133         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9134 }
9135
9136 #[test]
9137 fn test_keysend_payments_to_public_node() {
9138         let chanmon_cfgs = create_chanmon_cfgs(2);
9139         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9140         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9141         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9142
9143         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9144         let network_graph = nodes[0].network_graph;
9145         let payer_pubkey = nodes[0].node.get_our_node_id();
9146         let payee_pubkey = nodes[1].node.get_our_node_id();
9147         let route_params = RouteParameters {
9148                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9149                 final_value_msat: 10000,
9150                 final_cltv_expiry_delta: 40,
9151         };
9152         let scorer = test_utils::TestScorer::with_penalty(0);
9153         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9154         let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9155
9156         let test_preimage = PaymentPreimage([42; 32]);
9157         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage), PaymentId(test_preimage.0)).unwrap();
9158         check_added_monitors!(nodes[0], 1);
9159         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9160         assert_eq!(events.len(), 1);
9161         let event = events.pop().unwrap();
9162         let path = vec![&nodes[1]];
9163         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9164         claim_payment(&nodes[0], &path, test_preimage);
9165 }
9166
9167 #[test]
9168 fn test_keysend_payments_to_private_node() {
9169         let chanmon_cfgs = create_chanmon_cfgs(2);
9170         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9171         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9172         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9173
9174         let payer_pubkey = nodes[0].node.get_our_node_id();
9175         let payee_pubkey = nodes[1].node.get_our_node_id();
9176         nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
9177         nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
9178
9179         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], channelmanager::provided_init_features(), channelmanager::provided_init_features());
9180         let route_params = RouteParameters {
9181                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9182                 final_value_msat: 10000,
9183                 final_cltv_expiry_delta: 40,
9184         };
9185         let network_graph = nodes[0].network_graph;
9186         let first_hops = nodes[0].node.list_usable_channels();
9187         let scorer = test_utils::TestScorer::with_penalty(0);
9188         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9189         let route = find_route(
9190                 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9191                 nodes[0].logger, &scorer, &random_seed_bytes
9192         ).unwrap();
9193
9194         let test_preimage = PaymentPreimage([42; 32]);
9195         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage), PaymentId(test_preimage.0)).unwrap();
9196         check_added_monitors!(nodes[0], 1);
9197         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9198         assert_eq!(events.len(), 1);
9199         let event = events.pop().unwrap();
9200         let path = vec![&nodes[1]];
9201         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9202         claim_payment(&nodes[0], &path, test_preimage);
9203 }
9204
9205 #[test]
9206 fn test_double_partial_claim() {
9207         // Test what happens if a node receives a payment, generates a PaymentReceived event, the HTLCs
9208         // time out, the sender resends only some of the MPP parts, then the user processes the
9209         // PaymentReceived event, ensuring they don't inadvertently claim only part of the full payment
9210         // amount.
9211         let chanmon_cfgs = create_chanmon_cfgs(4);
9212         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9213         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9214         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9215
9216         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9217         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9218         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9219         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
9220
9221         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9222         assert_eq!(route.paths.len(), 2);
9223         route.paths.sort_by(|path_a, _| {
9224                 // Sort the path so that the path through nodes[1] comes first
9225                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9226                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9227         });
9228
9229         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9230         // nodes[3] has now received a PaymentReceived event...which it will take some (exorbitant)
9231         // amount of time to respond to.
9232
9233         // Connect some blocks to time out the payment
9234         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9235         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9236
9237         let failed_destinations = vec![
9238                 HTLCDestination::FailedPayment { payment_hash },
9239                 HTLCDestination::FailedPayment { payment_hash },
9240         ];
9241         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9242
9243         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
9244
9245         // nodes[1] now retries one of the two paths...
9246         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9247         check_added_monitors!(nodes[0], 2);
9248
9249         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9250         assert_eq!(events.len(), 2);
9251         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
9252
9253         // At this point nodes[3] has received one half of the payment, and the user goes to handle
9254         // that PaymentReceived event they got hours ago and never handled...we should refuse to claim.
9255         nodes[3].node.claim_funds(payment_preimage);
9256         check_added_monitors!(nodes[3], 0);
9257         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9258 }
9259
9260 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9261 #[derive(Clone, Copy, PartialEq)]
9262 enum ExposureEvent {
9263         /// Breach occurs at HTLC forwarding (see `send_htlc`)
9264         AtHTLCForward,
9265         /// Breach occurs at HTLC reception (see `update_add_htlc`)
9266         AtHTLCReception,
9267         /// Breach occurs at outbound update_fee (see `send_update_fee`)
9268         AtUpdateFeeOutbound,
9269 }
9270
9271 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9272         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9273         // policy.
9274         //
9275         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9276         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9277         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9278         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9279         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9280         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9281         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9282         // might be available again for HTLC processing once the dust bandwidth has cleared up.
9283
9284         let chanmon_cfgs = create_chanmon_cfgs(2);
9285         let mut config = test_default_channel_config();
9286         config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9287         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9288         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9289         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9290
9291         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9292         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9293         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9294         open_channel.max_accepted_htlcs = 60;
9295         if on_holder_tx {
9296                 open_channel.dust_limit_satoshis = 546;
9297         }
9298         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
9299         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9300         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
9301
9302         let opt_anchors = false;
9303
9304         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9305
9306         if on_holder_tx {
9307                 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
9308                         chan.holder_dust_limit_satoshis = 546;
9309                 }
9310         }
9311
9312         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9313         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()));
9314         check_added_monitors!(nodes[1], 1);
9315
9316         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()));
9317         check_added_monitors!(nodes[0], 1);
9318
9319         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9320         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9321         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9322
9323         let dust_buffer_feerate = {
9324                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
9325                 let chan = chan_lock.by_id.get(&channel_id).unwrap();
9326                 chan.get_dust_buffer_feerate(None) as u64
9327         };
9328         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;
9329         let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9330
9331         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;
9332         let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9333
9334         let dust_htlc_on_counterparty_tx: u64 = 25;
9335         let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9336
9337         if on_holder_tx {
9338                 if dust_outbound_balance {
9339                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9340                         // Outbound dust balance: 4372 sats
9341                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9342                         for i in 0..dust_outbound_htlc_on_holder_tx {
9343                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9344                                 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); }
9345                         }
9346                 } else {
9347                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9348                         // Inbound dust balance: 4372 sats
9349                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9350                         for _ in 0..dust_inbound_htlc_on_holder_tx {
9351                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9352                         }
9353                 }
9354         } else {
9355                 if dust_outbound_balance {
9356                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9357                         // Outbound dust balance: 5000 sats
9358                         for i in 0..dust_htlc_on_counterparty_tx {
9359                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9360                                 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); }
9361                         }
9362                 } else {
9363                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9364                         // Inbound dust balance: 5000 sats
9365                         for _ in 0..dust_htlc_on_counterparty_tx {
9366                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9367                         }
9368                 }
9369         }
9370
9371         let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9372         if exposure_breach_event == ExposureEvent::AtHTLCForward {
9373                 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 });
9374                 let mut config = UserConfig::default();
9375                 // With default dust exposure: 5000 sats
9376                 if on_holder_tx {
9377                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9378                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9379                         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)));
9380                 } else {
9381                         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)));
9382                 }
9383         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9384                 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 });
9385                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9386                 check_added_monitors!(nodes[1], 1);
9387                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9388                 assert_eq!(events.len(), 1);
9389                 let payment_event = SendEvent::from_event(events.remove(0));
9390                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9391                 // With default dust exposure: 5000 sats
9392                 if on_holder_tx {
9393                         // Outbound dust balance: 6399 sats
9394                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9395                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9396                         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);
9397                 } else {
9398                         // Outbound dust balance: 5200 sats
9399                         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);
9400                 }
9401         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9402                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
9403                 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", ); }
9404                 {
9405                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9406                         *feerate_lock = *feerate_lock * 10;
9407                 }
9408                 nodes[0].node.timer_tick_occurred();
9409                 check_added_monitors!(nodes[0], 1);
9410                 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);
9411         }
9412
9413         let _ = nodes[0].node.get_and_clear_pending_msg_events();
9414         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9415         added_monitors.clear();
9416 }
9417
9418 #[test]
9419 fn test_max_dust_htlc_exposure() {
9420         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9421         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9422         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9423         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9424         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9425         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9426         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9427         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9428         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9429         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9430         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9431         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
9432 }
9433
9434 #[test]
9435 fn test_non_final_funding_tx() {
9436         let chanmon_cfgs = create_chanmon_cfgs(2);
9437         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9438         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9439         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9440
9441         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9442         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9443         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel_message);
9444         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9445         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel_message);
9446
9447         let best_height = nodes[0].node.best_block.read().unwrap().height();
9448
9449         let chan_id = *nodes[0].network_chan_count.borrow();
9450         let events = nodes[0].node.get_and_clear_pending_events();
9451         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9452         assert_eq!(events.len(), 1);
9453         let mut tx = match events[0] {
9454                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9455                         // Timelock the transaction _beyond_ the best client height + 2.
9456                         Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 3), input: vec![input], output: vec![TxOut {
9457                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9458                         }]}
9459                 },
9460                 _ => panic!("Unexpected event"),
9461         };
9462         // Transaction should fail as it's evaluated as non-final for propagation.
9463         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9464                 Err(APIError::APIMisuseError { err }) => {
9465                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9466                 },
9467                 _ => panic!()
9468         }
9469
9470         // However, transaction should be accepted if it's in a +2 headroom from best block.
9471         tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9472         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9473         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9474 }
9475
9476 #[test]
9477 fn accept_busted_but_better_fee() {
9478         // If a peer sends us a fee update that is too low, but higher than our previous channel
9479         // feerate, we should accept it. In the future we may want to consider closing the channel
9480         // later, but for now we only accept the update.
9481         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9482         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9483         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9484         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9485
9486         create_chan_between_nodes(&nodes[0], &nodes[1], channelmanager::provided_init_features(), channelmanager::provided_init_features());
9487
9488         // Set nodes[1] to expect 5,000 sat/kW.
9489         {
9490                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9491                 *feerate_lock = 5000;
9492         }
9493
9494         // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9495         {
9496                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9497                 *feerate_lock = 1000;
9498         }
9499         nodes[0].node.timer_tick_occurred();
9500         check_added_monitors!(nodes[0], 1);
9501
9502         let events = nodes[0].node.get_and_clear_pending_msg_events();
9503         assert_eq!(events.len(), 1);
9504         match events[0] {
9505                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9506                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9507                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9508                 },
9509                 _ => panic!("Unexpected event"),
9510         };
9511
9512         // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9513         // it.
9514         {
9515                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9516                 *feerate_lock = 2000;
9517         }
9518         nodes[0].node.timer_tick_occurred();
9519         check_added_monitors!(nodes[0], 1);
9520
9521         let events = nodes[0].node.get_and_clear_pending_msg_events();
9522         assert_eq!(events.len(), 1);
9523         match events[0] {
9524                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9525                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9526                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9527                 },
9528                 _ => panic!("Unexpected event"),
9529         };
9530
9531         // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9532         // channel.
9533         {
9534                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9535                 *feerate_lock = 1000;
9536         }
9537         nodes[0].node.timer_tick_occurred();
9538         check_added_monitors!(nodes[0], 1);
9539
9540         let events = nodes[0].node.get_and_clear_pending_msg_events();
9541         assert_eq!(events.len(), 1);
9542         match events[0] {
9543                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9544                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9545                         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9546                                 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() });
9547                         check_closed_broadcast!(nodes[1], true);
9548                         check_added_monitors!(nodes[1], 1);
9549                 },
9550                 _ => panic!("Unexpected event"),
9551         };
9552 }