Merge pull request #2083 from wpaulino/events-module
[rust-lightning] / lightning / src / ln / functional_tests.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
13
14 use crate::chain;
15 use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Listen, Watch};
16 use crate::chain::chaininterface::LowerBoundedFeeEstimator;
17 use crate::chain::channelmonitor;
18 use crate::chain::channelmonitor::{CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
19 use crate::chain::transaction::OutPoint;
20 use crate::chain::keysinterface::{ChannelSigner, EcdsaChannelSigner, EntropySource};
21 use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose, ClosureReason, HTLCDestination};
22 use crate::ln::{PaymentPreimage, PaymentSecret, PaymentHash};
23 use crate::ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT};
24 use crate::ln::channelmanager::{self, PaymentId, RAACommitmentOrder, PaymentSendFailure, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA};
25 use crate::ln::channel::{Channel, ChannelError};
26 use crate::ln::{chan_utils, onion_utils};
27 use crate::ln::chan_utils::{OFFERED_HTLC_SCRIPT_WEIGHT, htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
28 use crate::routing::gossip::{NetworkGraph, NetworkUpdate};
29 use crate::routing::router::{PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
30 use crate::ln::features::{ChannelFeatures, NodeFeatures};
31 use crate::ln::msgs;
32 use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
33 use crate::util::enforcing_trait_impls::EnforcingSigner;
34 use crate::util::test_utils;
35 use crate::util::errors::APIError;
36 use crate::util::ser::{Writeable, ReadableArgs};
37 use crate::util::string::UntrustedString;
38 use crate::util::config::UserConfig;
39
40 use bitcoin::hash_types::BlockHash;
41 use bitcoin::blockdata::block::{Block, BlockHeader};
42 use bitcoin::blockdata::script::{Builder, Script};
43 use bitcoin::blockdata::opcodes;
44 use bitcoin::blockdata::constants::genesis_block;
45 use bitcoin::network::constants::Network;
46 use bitcoin::{PackedLockTime, Sequence, Transaction, TxIn, TxMerkleNode, TxOut, Witness};
47 use bitcoin::OutPoint as BitcoinOutPoint;
48
49 use bitcoin::secp256k1::Secp256k1;
50 use bitcoin::secp256k1::{PublicKey,SecretKey};
51
52 use regex;
53
54 use crate::io;
55 use crate::prelude::*;
56 use alloc::collections::BTreeSet;
57 use core::default::Default;
58 use core::iter::repeat;
59 use bitcoin::hashes::Hash;
60 use crate::sync::{Arc, Mutex};
61
62 use crate::ln::functional_test_utils::*;
63 use crate::ln::chan_utils::CommitmentTransaction;
64
65 #[test]
66 fn test_insane_channel_opens() {
67         // Stand up a network of 2 nodes
68         use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
69         let mut cfg = UserConfig::default();
70         cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
71         let chanmon_cfgs = create_chanmon_cfgs(2);
72         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
73         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
74         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
75
76         // Instantiate channel parameters where we push the maximum msats given our
77         // funding satoshis
78         let channel_value_sat = 31337; // same as funding satoshis
79         let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
80         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
81
82         // Have node0 initiate a channel to node1 with aforementioned parameters
83         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
84
85         // Extract the channel open message from node0 to node1
86         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
87
88         // Test helper that asserts we get the correct error string given a mutator
89         // that supposedly makes the channel open message insane
90         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
91                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &message_mutator(open_channel_message.clone()));
92                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
93                 assert_eq!(msg_events.len(), 1);
94                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
95                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
96                         match action {
97                                 &ErrorAction::SendErrorMessage { .. } => {
98                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager", expected_regex, 1);
99                                 },
100                                 _ => panic!("unexpected event!"),
101                         }
102                 } else { assert!(false); }
103         };
104
105         use crate::ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
106
107         // Test all mutations that would make the channel open message insane
108         insane_open_helper(format!("Per our config, funding must be at most {}. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1, TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2; msg });
109         insane_open_helper(format!("Funding must be smaller than the total bitcoin supply. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS; msg });
110
111         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
112
113         insane_open_helper(r"push_msat \d+ was larger than channel amount minus reserve \(\d+\)", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
114
115         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
116
117         insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
118
119         insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
120
121         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
122
123         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
124 }
125
126 #[test]
127 fn test_funding_exceeds_no_wumbo_limit() {
128         // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
129         // them.
130         use crate::ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
131         let chanmon_cfgs = create_chanmon_cfgs(2);
132         let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
133         *node_cfgs[1].override_init_features.borrow_mut() = Some(channelmanager::provided_init_features(&test_default_channel_config()).clear_wumbo());
134         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
135         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
136
137         match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
138                 Err(APIError::APIMisuseError { err }) => {
139                         assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
140                 },
141                 _ => panic!()
142         }
143 }
144
145 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
146         // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
147         // but only for them. Because some LSPs do it with some level of trust of the clients (for a
148         // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
149         // in normal testing, we test it explicitly here.
150         let chanmon_cfgs = create_chanmon_cfgs(2);
151         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
152         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
153         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
154         let default_config = UserConfig::default();
155
156         // Have node0 initiate a channel to node1 with aforementioned parameters
157         let mut push_amt = 100_000_000;
158         let feerate_per_kw = 253;
159         let opt_anchors = false;
160         push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
161         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
162
163         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, if send_from_initiator { 0 } else { push_amt }, 42, None).unwrap();
164         let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
165         if !send_from_initiator {
166                 open_channel_message.channel_reserve_satoshis = 0;
167                 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
168         }
169         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
170
171         // Extract the channel accept message from node1 to node0
172         let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
173         if send_from_initiator {
174                 accept_channel_message.channel_reserve_satoshis = 0;
175                 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
176         }
177         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
178         {
179                 let sender_node = if send_from_initiator { &nodes[1] } else { &nodes[0] };
180                 let counterparty_node = if send_from_initiator { &nodes[0] } else { &nodes[1] };
181                 let mut sender_node_per_peer_lock;
182                 let mut sender_node_peer_state_lock;
183                 let mut chan = get_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
184                 chan.holder_selected_channel_reserve_satoshis = 0;
185                 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
186         }
187
188         let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
189         let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
190         create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
191
192         // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
193         // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
194         if send_from_initiator {
195                 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
196                         // Note that for outbound channels we have to consider the commitment tx fee and the
197                         // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
198                         // well as an additional HTLC.
199                         - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
200         } else {
201                 send_payment(&nodes[1], &[&nodes[0]], push_amt);
202         }
203 }
204
205 #[test]
206 fn test_counterparty_no_reserve() {
207         do_test_counterparty_no_reserve(true);
208         do_test_counterparty_no_reserve(false);
209 }
210
211 #[test]
212 fn test_async_inbound_update_fee() {
213         let chanmon_cfgs = create_chanmon_cfgs(2);
214         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
215         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
216         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
217         create_announced_chan_between_nodes(&nodes, 0, 1);
218
219         // balancing
220         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
221
222         // A                                        B
223         // update_fee                            ->
224         // send (1) commitment_signed            -.
225         //                                       <- update_add_htlc/commitment_signed
226         // send (2) RAA (awaiting remote revoke) -.
227         // (1) commitment_signed is delivered    ->
228         //                                       .- send (3) RAA (awaiting remote revoke)
229         // (2) RAA is delivered                  ->
230         //                                       .- send (4) commitment_signed
231         //                                       <- (3) RAA is delivered
232         // send (5) commitment_signed            -.
233         //                                       <- (4) commitment_signed is delivered
234         // send (6) RAA                          -.
235         // (5) commitment_signed is delivered    ->
236         //                                       <- RAA
237         // (6) RAA is delivered                  ->
238
239         // First nodes[0] generates an update_fee
240         {
241                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
242                 *feerate_lock += 20;
243         }
244         nodes[0].node.timer_tick_occurred();
245         check_added_monitors!(nodes[0], 1);
246
247         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
248         assert_eq!(events_0.len(), 1);
249         let (update_msg, commitment_signed) = match events_0[0] { // (1)
250                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
251                         (update_fee.as_ref(), commitment_signed)
252                 },
253                 _ => panic!("Unexpected event"),
254         };
255
256         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
257
258         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
259         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
260         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
261         check_added_monitors!(nodes[1], 1);
262
263         let payment_event = {
264                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
265                 assert_eq!(events_1.len(), 1);
266                 SendEvent::from_event(events_1.remove(0))
267         };
268         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
269         assert_eq!(payment_event.msgs.len(), 1);
270
271         // ...now when the messages get delivered everyone should be happy
272         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
273         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
274         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
275         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
276         check_added_monitors!(nodes[0], 1);
277
278         // deliver(1), generate (3):
279         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
280         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
281         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
282         check_added_monitors!(nodes[1], 1);
283
284         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
285         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
286         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
287         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
288         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
289         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
290         assert!(bs_update.update_fee.is_none()); // (4)
291         check_added_monitors!(nodes[1], 1);
292
293         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
294         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
295         assert!(as_update.update_add_htlcs.is_empty()); // (5)
296         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
297         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
298         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
299         assert!(as_update.update_fee.is_none()); // (5)
300         check_added_monitors!(nodes[0], 1);
301
302         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
303         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
304         // only (6) so get_event_msg's assert(len == 1) passes
305         check_added_monitors!(nodes[0], 1);
306
307         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
308         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
309         check_added_monitors!(nodes[1], 1);
310
311         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
312         check_added_monitors!(nodes[0], 1);
313
314         let events_2 = nodes[0].node.get_and_clear_pending_events();
315         assert_eq!(events_2.len(), 1);
316         match events_2[0] {
317                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
318                 _ => panic!("Unexpected event"),
319         }
320
321         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
322         check_added_monitors!(nodes[1], 1);
323 }
324
325 #[test]
326 fn test_update_fee_unordered_raa() {
327         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
328         // crash in an earlier version of the update_fee patch)
329         let chanmon_cfgs = create_chanmon_cfgs(2);
330         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
331         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
332         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
333         create_announced_chan_between_nodes(&nodes, 0, 1);
334
335         // balancing
336         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
337
338         // First nodes[0] generates an update_fee
339         {
340                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
341                 *feerate_lock += 20;
342         }
343         nodes[0].node.timer_tick_occurred();
344         check_added_monitors!(nodes[0], 1);
345
346         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
347         assert_eq!(events_0.len(), 1);
348         let update_msg = match events_0[0] { // (1)
349                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
350                         update_fee.as_ref()
351                 },
352                 _ => panic!("Unexpected event"),
353         };
354
355         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
356
357         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
358         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
359         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
360         check_added_monitors!(nodes[1], 1);
361
362         let payment_event = {
363                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
364                 assert_eq!(events_1.len(), 1);
365                 SendEvent::from_event(events_1.remove(0))
366         };
367         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
368         assert_eq!(payment_event.msgs.len(), 1);
369
370         // ...now when the messages get delivered everyone should be happy
371         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
372         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
373         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
374         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
375         check_added_monitors!(nodes[0], 1);
376
377         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
378         check_added_monitors!(nodes[1], 1);
379
380         // We can't continue, sadly, because our (1) now has a bogus signature
381 }
382
383 #[test]
384 fn test_multi_flight_update_fee() {
385         let chanmon_cfgs = create_chanmon_cfgs(2);
386         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
387         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
388         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
389         create_announced_chan_between_nodes(&nodes, 0, 1);
390
391         // A                                        B
392         // update_fee/commitment_signed          ->
393         //                                       .- send (1) RAA and (2) commitment_signed
394         // update_fee (never committed)          ->
395         // (3) update_fee                        ->
396         // We have to manually generate the above update_fee, it is allowed by the protocol but we
397         // don't track which updates correspond to which revoke_and_ack responses so we're in
398         // AwaitingRAA mode and will not generate the update_fee yet.
399         //                                       <- (1) RAA delivered
400         // (3) is generated and send (4) CS      -.
401         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
402         // know the per_commitment_point to use for it.
403         //                                       <- (2) commitment_signed delivered
404         // revoke_and_ack                        ->
405         //                                          B should send no response here
406         // (4) commitment_signed delivered       ->
407         //                                       <- RAA/commitment_signed delivered
408         // revoke_and_ack                        ->
409
410         // First nodes[0] generates an update_fee
411         let initial_feerate;
412         {
413                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
414                 initial_feerate = *feerate_lock;
415                 *feerate_lock = initial_feerate + 20;
416         }
417         nodes[0].node.timer_tick_occurred();
418         check_added_monitors!(nodes[0], 1);
419
420         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
421         assert_eq!(events_0.len(), 1);
422         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
423                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
424                         (update_fee.as_ref().unwrap(), commitment_signed)
425                 },
426                 _ => panic!("Unexpected event"),
427         };
428
429         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
430         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
431         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
432         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
433         check_added_monitors!(nodes[1], 1);
434
435         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
436         // transaction:
437         {
438                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
439                 *feerate_lock = initial_feerate + 40;
440         }
441         nodes[0].node.timer_tick_occurred();
442         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
443         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
444
445         // Create the (3) update_fee message that nodes[0] will generate before it does...
446         let mut update_msg_2 = msgs::UpdateFee {
447                 channel_id: update_msg_1.channel_id.clone(),
448                 feerate_per_kw: (initial_feerate + 30) as u32,
449         };
450
451         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
452
453         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
454         // Deliver (3)
455         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
456
457         // Deliver (1), generating (3) and (4)
458         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
459         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
460         check_added_monitors!(nodes[0], 1);
461         assert!(as_second_update.update_add_htlcs.is_empty());
462         assert!(as_second_update.update_fulfill_htlcs.is_empty());
463         assert!(as_second_update.update_fail_htlcs.is_empty());
464         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
465         // Check that the update_fee newly generated matches what we delivered:
466         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
467         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
468
469         // Deliver (2) commitment_signed
470         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
471         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
472         check_added_monitors!(nodes[0], 1);
473         // No commitment_signed so get_event_msg's assert(len == 1) passes
474
475         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
476         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
477         check_added_monitors!(nodes[1], 1);
478
479         // Delever (4)
480         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
481         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
482         check_added_monitors!(nodes[1], 1);
483
484         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
485         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
486         check_added_monitors!(nodes[0], 1);
487
488         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
489         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
490         // No commitment_signed so get_event_msg's assert(len == 1) passes
491         check_added_monitors!(nodes[0], 1);
492
493         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
494         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
495         check_added_monitors!(nodes[1], 1);
496 }
497
498 fn do_test_sanity_on_in_flight_opens(steps: u8) {
499         // Previously, we had issues deserializing channels when we hadn't connected the first block
500         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
501         // serialization round-trips and simply do steps towards opening a channel and then drop the
502         // Node objects.
503
504         let chanmon_cfgs = create_chanmon_cfgs(2);
505         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
506         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
507         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
508
509         if steps & 0b1000_0000 != 0{
510                 let block = Block {
511                         header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
512                         txdata: vec![],
513                 };
514                 connect_block(&nodes[0], &block);
515                 connect_block(&nodes[1], &block);
516         }
517
518         if steps & 0x0f == 0 { return; }
519         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
520         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
521
522         if steps & 0x0f == 1 { return; }
523         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
524         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
525
526         if steps & 0x0f == 2 { return; }
527         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
528
529         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
530
531         if steps & 0x0f == 3 { return; }
532         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
533         check_added_monitors!(nodes[0], 0);
534         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
535
536         if steps & 0x0f == 4 { return; }
537         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
538         {
539                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
540                 assert_eq!(added_monitors.len(), 1);
541                 assert_eq!(added_monitors[0].0, funding_output);
542                 added_monitors.clear();
543         }
544         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
545
546         if steps & 0x0f == 5 { return; }
547         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
548         {
549                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
550                 assert_eq!(added_monitors.len(), 1);
551                 assert_eq!(added_monitors[0].0, funding_output);
552                 added_monitors.clear();
553         }
554
555         let events_4 = nodes[0].node.get_and_clear_pending_events();
556         assert_eq!(events_4.len(), 0);
557
558         if steps & 0x0f == 6 { return; }
559         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
560
561         if steps & 0x0f == 7 { return; }
562         confirm_transaction_at(&nodes[0], &tx, 2);
563         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
564         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
565         expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
566 }
567
568 #[test]
569 fn test_sanity_on_in_flight_opens() {
570         do_test_sanity_on_in_flight_opens(0);
571         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
572         do_test_sanity_on_in_flight_opens(1);
573         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
574         do_test_sanity_on_in_flight_opens(2);
575         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
576         do_test_sanity_on_in_flight_opens(3);
577         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
578         do_test_sanity_on_in_flight_opens(4);
579         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
580         do_test_sanity_on_in_flight_opens(5);
581         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
582         do_test_sanity_on_in_flight_opens(6);
583         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
584         do_test_sanity_on_in_flight_opens(7);
585         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
586         do_test_sanity_on_in_flight_opens(8);
587         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
588 }
589
590 #[test]
591 fn test_update_fee_vanilla() {
592         let chanmon_cfgs = create_chanmon_cfgs(2);
593         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
594         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
595         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
596         create_announced_chan_between_nodes(&nodes, 0, 1);
597
598         {
599                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
600                 *feerate_lock += 25;
601         }
602         nodes[0].node.timer_tick_occurred();
603         check_added_monitors!(nodes[0], 1);
604
605         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
606         assert_eq!(events_0.len(), 1);
607         let (update_msg, commitment_signed) = match events_0[0] {
608                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
609                         (update_fee.as_ref(), commitment_signed)
610                 },
611                 _ => panic!("Unexpected event"),
612         };
613         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
614
615         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
616         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
617         check_added_monitors!(nodes[1], 1);
618
619         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
620         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
621         check_added_monitors!(nodes[0], 1);
622
623         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
624         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
625         // No commitment_signed so get_event_msg's assert(len == 1) passes
626         check_added_monitors!(nodes[0], 1);
627
628         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
629         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
630         check_added_monitors!(nodes[1], 1);
631 }
632
633 #[test]
634 fn test_update_fee_that_funder_cannot_afford() {
635         let chanmon_cfgs = create_chanmon_cfgs(2);
636         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
637         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
638         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
639         let channel_value = 5000;
640         let push_sats = 700;
641         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000);
642         let channel_id = chan.2;
643         let secp_ctx = Secp256k1::new();
644         let default_config = UserConfig::default();
645         let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
646
647         let opt_anchors = false;
648
649         // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
650         // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
651         // calculate two different feerates here - the expected local limit as well as the expected
652         // remote limit.
653         let feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / (commitment_tx_base_weight(opt_anchors) + CONCURRENT_INBOUND_HTLC_FEE_BUFFER as u64 * COMMITMENT_TX_WEIGHT_PER_HTLC)) as u32;
654         let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
655         {
656                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
657                 *feerate_lock = feerate;
658         }
659         nodes[0].node.timer_tick_occurred();
660         check_added_monitors!(nodes[0], 1);
661         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
662
663         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
664
665         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
666
667         // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
668         {
669                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
670
671                 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
672                 assert_eq!(commitment_tx.output.len(), 2);
673                 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
674                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
675                 actual_fee = channel_value - actual_fee;
676                 assert_eq!(total_fee, actual_fee);
677         }
678
679         {
680                 // Increment the feerate by a small constant, accounting for rounding errors
681                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
682                 *feerate_lock += 4;
683         }
684         nodes[0].node.timer_tick_occurred();
685         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
686         check_added_monitors!(nodes[0], 0);
687
688         const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
689
690         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
691         // needed to sign the new commitment tx and (2) sign the new commitment tx.
692         let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
693                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
694                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
695                 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
696                 let chan_signer = local_chan.get_signer();
697                 let pubkeys = chan_signer.pubkeys();
698                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
699                  pubkeys.funding_pubkey)
700         };
701         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
702                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
703                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
704                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
705                 let chan_signer = remote_chan.get_signer();
706                 let pubkeys = chan_signer.pubkeys();
707                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
708                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
709                  pubkeys.funding_pubkey)
710         };
711
712         // Assemble the set of keys we can use for signatures for our commitment_signed message.
713         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
714                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
715
716         let res = {
717                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
718                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
719                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
720                 let local_chan_signer = local_chan.get_signer();
721                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
722                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
723                         INITIAL_COMMITMENT_NUMBER - 1,
724                         push_sats,
725                         channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
726                         opt_anchors, local_funding, remote_funding,
727                         commit_tx_keys.clone(),
728                         non_buffer_feerate + 4,
729                         &mut htlcs,
730                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
731                 );
732                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
733         };
734
735         let commit_signed_msg = msgs::CommitmentSigned {
736                 channel_id: chan.2,
737                 signature: res.0,
738                 htlc_signatures: res.1
739         };
740
741         let update_fee = msgs::UpdateFee {
742                 channel_id: chan.2,
743                 feerate_per_kw: non_buffer_feerate + 4,
744         };
745
746         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
747
748         //While producing the commitment_signed response after handling a received update_fee request the
749         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
750         //Should produce and error.
751         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
752         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
753         check_added_monitors!(nodes[1], 1);
754         check_closed_broadcast!(nodes[1], true);
755         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
756 }
757
758 #[test]
759 fn test_update_fee_with_fundee_update_add_htlc() {
760         let chanmon_cfgs = create_chanmon_cfgs(2);
761         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
762         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
763         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
764         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
765
766         // balancing
767         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
768
769         {
770                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
771                 *feerate_lock += 20;
772         }
773         nodes[0].node.timer_tick_occurred();
774         check_added_monitors!(nodes[0], 1);
775
776         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
777         assert_eq!(events_0.len(), 1);
778         let (update_msg, commitment_signed) = match events_0[0] {
779                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
780                         (update_fee.as_ref(), commitment_signed)
781                 },
782                 _ => panic!("Unexpected event"),
783         };
784         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
785         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
786         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
787         check_added_monitors!(nodes[1], 1);
788
789         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
790
791         // nothing happens since node[1] is in AwaitingRemoteRevoke
792         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
793         {
794                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
795                 assert_eq!(added_monitors.len(), 0);
796                 added_monitors.clear();
797         }
798         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
799         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
800         // node[1] has nothing to do
801
802         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
803         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
804         check_added_monitors!(nodes[0], 1);
805
806         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
807         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
808         // No commitment_signed so get_event_msg's assert(len == 1) passes
809         check_added_monitors!(nodes[0], 1);
810         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
811         check_added_monitors!(nodes[1], 1);
812         // AwaitingRemoteRevoke ends here
813
814         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
815         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
816         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
817         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
818         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
819         assert_eq!(commitment_update.update_fee.is_none(), true);
820
821         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
822         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
823         check_added_monitors!(nodes[0], 1);
824         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
825
826         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
827         check_added_monitors!(nodes[1], 1);
828         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
829
830         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
831         check_added_monitors!(nodes[1], 1);
832         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
833         // No commitment_signed so get_event_msg's assert(len == 1) passes
834
835         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
836         check_added_monitors!(nodes[0], 1);
837         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
838
839         expect_pending_htlcs_forwardable!(nodes[0]);
840
841         let events = nodes[0].node.get_and_clear_pending_events();
842         assert_eq!(events.len(), 1);
843         match events[0] {
844                 Event::PaymentClaimable { .. } => { },
845                 _ => panic!("Unexpected event"),
846         };
847
848         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
849
850         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
851         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
852         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
853         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
854         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
855 }
856
857 #[test]
858 fn test_update_fee() {
859         let chanmon_cfgs = create_chanmon_cfgs(2);
860         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
861         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
862         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
863         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
864         let channel_id = chan.2;
865
866         // A                                        B
867         // (1) update_fee/commitment_signed      ->
868         //                                       <- (2) revoke_and_ack
869         //                                       .- send (3) commitment_signed
870         // (4) update_fee/commitment_signed      ->
871         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
872         //                                       <- (3) commitment_signed delivered
873         // send (6) revoke_and_ack               -.
874         //                                       <- (5) deliver revoke_and_ack
875         // (6) deliver revoke_and_ack            ->
876         //                                       .- send (7) commitment_signed in response to (4)
877         //                                       <- (7) deliver commitment_signed
878         // revoke_and_ack                        ->
879
880         // Create and deliver (1)...
881         let feerate;
882         {
883                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
884                 feerate = *feerate_lock;
885                 *feerate_lock = feerate + 20;
886         }
887         nodes[0].node.timer_tick_occurred();
888         check_added_monitors!(nodes[0], 1);
889
890         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
891         assert_eq!(events_0.len(), 1);
892         let (update_msg, commitment_signed) = match events_0[0] {
893                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
894                         (update_fee.as_ref(), commitment_signed)
895                 },
896                 _ => panic!("Unexpected event"),
897         };
898         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
899
900         // Generate (2) and (3):
901         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
902         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
903         check_added_monitors!(nodes[1], 1);
904
905         // Deliver (2):
906         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
907         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
908         check_added_monitors!(nodes[0], 1);
909
910         // Create and deliver (4)...
911         {
912                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
913                 *feerate_lock = feerate + 30;
914         }
915         nodes[0].node.timer_tick_occurred();
916         check_added_monitors!(nodes[0], 1);
917         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
918         assert_eq!(events_0.len(), 1);
919         let (update_msg, commitment_signed) = match events_0[0] {
920                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
921                         (update_fee.as_ref(), commitment_signed)
922                 },
923                 _ => panic!("Unexpected event"),
924         };
925
926         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
927         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
928         check_added_monitors!(nodes[1], 1);
929         // ... creating (5)
930         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
931         // No commitment_signed so get_event_msg's assert(len == 1) passes
932
933         // Handle (3), creating (6):
934         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
935         check_added_monitors!(nodes[0], 1);
936         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
937         // No commitment_signed so get_event_msg's assert(len == 1) passes
938
939         // Deliver (5):
940         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
941         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
942         check_added_monitors!(nodes[0], 1);
943
944         // Deliver (6), creating (7):
945         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
946         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
947         assert!(commitment_update.update_add_htlcs.is_empty());
948         assert!(commitment_update.update_fulfill_htlcs.is_empty());
949         assert!(commitment_update.update_fail_htlcs.is_empty());
950         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
951         assert!(commitment_update.update_fee.is_none());
952         check_added_monitors!(nodes[1], 1);
953
954         // Deliver (7)
955         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
956         check_added_monitors!(nodes[0], 1);
957         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
958         // No commitment_signed so get_event_msg's assert(len == 1) passes
959
960         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
961         check_added_monitors!(nodes[1], 1);
962         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
963
964         assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
965         assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
966         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
967         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
968         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
969 }
970
971 #[test]
972 fn fake_network_test() {
973         // Simple test which builds a network of ChannelManagers, connects them to each other, and
974         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
975         let chanmon_cfgs = create_chanmon_cfgs(4);
976         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
977         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
978         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
979
980         // Create some initial channels
981         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
982         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
983         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
984
985         // Rebalance the network a bit by relaying one payment through all the channels...
986         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
987         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
988         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
989         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
990
991         // Send some more payments
992         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
993         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
994         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
995
996         // Test failure packets
997         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
998         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
999
1000         // Add a new channel that skips 3
1001         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1002
1003         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1004         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1005         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1006         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1007         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1008         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1009         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1010
1011         // Do some rebalance loop payments, simultaneously
1012         let mut hops = Vec::with_capacity(3);
1013         hops.push(RouteHop {
1014                 pubkey: nodes[2].node.get_our_node_id(),
1015                 node_features: NodeFeatures::empty(),
1016                 short_channel_id: chan_2.0.contents.short_channel_id,
1017                 channel_features: ChannelFeatures::empty(),
1018                 fee_msat: 0,
1019                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1020         });
1021         hops.push(RouteHop {
1022                 pubkey: nodes[3].node.get_our_node_id(),
1023                 node_features: NodeFeatures::empty(),
1024                 short_channel_id: chan_3.0.contents.short_channel_id,
1025                 channel_features: ChannelFeatures::empty(),
1026                 fee_msat: 0,
1027                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1028         });
1029         hops.push(RouteHop {
1030                 pubkey: nodes[1].node.get_our_node_id(),
1031                 node_features: nodes[1].node.node_features(),
1032                 short_channel_id: chan_4.0.contents.short_channel_id,
1033                 channel_features: nodes[1].node.channel_features(),
1034                 fee_msat: 1000000,
1035                 cltv_expiry_delta: TEST_FINAL_CLTV,
1036         });
1037         hops[1].fee_msat = chan_4.1.contents.fee_base_msat as u64 + chan_4.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1038         hops[0].fee_msat = chan_3.0.contents.fee_base_msat as u64 + chan_3.0.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1039         let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops], payment_params: None }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1040
1041         let mut hops = Vec::with_capacity(3);
1042         hops.push(RouteHop {
1043                 pubkey: nodes[3].node.get_our_node_id(),
1044                 node_features: NodeFeatures::empty(),
1045                 short_channel_id: chan_4.0.contents.short_channel_id,
1046                 channel_features: ChannelFeatures::empty(),
1047                 fee_msat: 0,
1048                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1049         });
1050         hops.push(RouteHop {
1051                 pubkey: nodes[2].node.get_our_node_id(),
1052                 node_features: NodeFeatures::empty(),
1053                 short_channel_id: chan_3.0.contents.short_channel_id,
1054                 channel_features: ChannelFeatures::empty(),
1055                 fee_msat: 0,
1056                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1057         });
1058         hops.push(RouteHop {
1059                 pubkey: nodes[1].node.get_our_node_id(),
1060                 node_features: nodes[1].node.node_features(),
1061                 short_channel_id: chan_2.0.contents.short_channel_id,
1062                 channel_features: nodes[1].node.channel_features(),
1063                 fee_msat: 1000000,
1064                 cltv_expiry_delta: TEST_FINAL_CLTV,
1065         });
1066         hops[1].fee_msat = chan_2.1.contents.fee_base_msat as u64 + chan_2.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1067         hops[0].fee_msat = chan_3.1.contents.fee_base_msat as u64 + chan_3.1.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1068         let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops], payment_params: None }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1069
1070         // Claim the rebalances...
1071         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1072         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1073
1074         // Close down the channels...
1075         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1076         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1077         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1078         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1079         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1080         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1081         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1082         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1083         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1084         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1085         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1086         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1087 }
1088
1089 #[test]
1090 fn holding_cell_htlc_counting() {
1091         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1092         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1093         // commitment dance rounds.
1094         let chanmon_cfgs = create_chanmon_cfgs(3);
1095         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1096         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1097         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1098         create_announced_chan_between_nodes(&nodes, 0, 1);
1099         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1100
1101         let mut payments = Vec::new();
1102         for _ in 0..crate::ln::channel::OUR_MAX_HTLCS {
1103                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1104                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
1105                 payments.push((payment_preimage, payment_hash));
1106         }
1107         check_added_monitors!(nodes[1], 1);
1108
1109         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1110         assert_eq!(events.len(), 1);
1111         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1112         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1113
1114         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1115         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1116         // another HTLC.
1117         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1118         {
1119                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)), true, APIError::ChannelUnavailable { ref err },
1120                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1121                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1122                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
1123         }
1124
1125         // This should also be true if we try to forward a payment.
1126         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1127         {
1128                 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1129                 check_added_monitors!(nodes[0], 1);
1130         }
1131
1132         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1133         assert_eq!(events.len(), 1);
1134         let payment_event = SendEvent::from_event(events.pop().unwrap());
1135         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1136
1137         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1138         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1139         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1140         // fails), the second will process the resulting failure and fail the HTLC backward.
1141         expect_pending_htlcs_forwardable!(nodes[1]);
1142         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
1143         check_added_monitors!(nodes[1], 1);
1144
1145         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1146         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1147         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1148
1149         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1150
1151         // Now forward all the pending HTLCs and claim them back
1152         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1153         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1154         check_added_monitors!(nodes[2], 1);
1155
1156         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1157         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1158         check_added_monitors!(nodes[1], 1);
1159         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1160
1161         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1162         check_added_monitors!(nodes[1], 1);
1163         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1164
1165         for ref update in as_updates.update_add_htlcs.iter() {
1166                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1167         }
1168         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1169         check_added_monitors!(nodes[2], 1);
1170         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1171         check_added_monitors!(nodes[2], 1);
1172         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1173
1174         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1175         check_added_monitors!(nodes[1], 1);
1176         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1177         check_added_monitors!(nodes[1], 1);
1178         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1179
1180         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1181         check_added_monitors!(nodes[2], 1);
1182
1183         expect_pending_htlcs_forwardable!(nodes[2]);
1184
1185         let events = nodes[2].node.get_and_clear_pending_events();
1186         assert_eq!(events.len(), payments.len());
1187         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1188                 match event {
1189                         &Event::PaymentClaimable { ref payment_hash, .. } => {
1190                                 assert_eq!(*payment_hash, *hash);
1191                         },
1192                         _ => panic!("Unexpected event"),
1193                 };
1194         }
1195
1196         for (preimage, _) in payments.drain(..) {
1197                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1198         }
1199
1200         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1201 }
1202
1203 #[test]
1204 fn duplicate_htlc_test() {
1205         // Test that we accept duplicate payment_hash HTLCs across the network and that
1206         // claiming/failing them are all separate and don't affect each other
1207         let chanmon_cfgs = create_chanmon_cfgs(6);
1208         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1209         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1210         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1211
1212         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1213         create_announced_chan_between_nodes(&nodes, 0, 3);
1214         create_announced_chan_between_nodes(&nodes, 1, 3);
1215         create_announced_chan_between_nodes(&nodes, 2, 3);
1216         create_announced_chan_between_nodes(&nodes, 3, 4);
1217         create_announced_chan_between_nodes(&nodes, 3, 5);
1218
1219         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1220
1221         *nodes[0].network_payment_count.borrow_mut() -= 1;
1222         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1223
1224         *nodes[0].network_payment_count.borrow_mut() -= 1;
1225         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1226
1227         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1228         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1229         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1230 }
1231
1232 #[test]
1233 fn test_duplicate_htlc_different_direction_onchain() {
1234         // Test that ChannelMonitor doesn't generate 2 preimage txn
1235         // when we have 2 HTLCs with same preimage that go across a node
1236         // in opposite directions, even with the same payment secret.
1237         let chanmon_cfgs = create_chanmon_cfgs(2);
1238         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1239         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1240         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1241
1242         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1243
1244         // balancing
1245         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1246
1247         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1248
1249         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1250         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1251         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1252
1253         // Provide preimage to node 0 by claiming payment
1254         nodes[0].node.claim_funds(payment_preimage);
1255         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1256         check_added_monitors!(nodes[0], 1);
1257
1258         // Broadcast node 1 commitment txn
1259         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1260
1261         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1262         let mut has_both_htlcs = 0; // check htlcs match ones committed
1263         for outp in remote_txn[0].output.iter() {
1264                 if outp.value == 800_000 / 1000 {
1265                         has_both_htlcs += 1;
1266                 } else if outp.value == 900_000 / 1000 {
1267                         has_both_htlcs += 1;
1268                 }
1269         }
1270         assert_eq!(has_both_htlcs, 2);
1271
1272         mine_transaction(&nodes[0], &remote_txn[0]);
1273         check_added_monitors!(nodes[0], 1);
1274         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1275         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1276
1277         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1278         assert_eq!(claim_txn.len(), 3);
1279
1280         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1281         check_spends!(claim_txn[1], remote_txn[0]);
1282         check_spends!(claim_txn[2], remote_txn[0]);
1283         let preimage_tx = &claim_txn[0];
1284         let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1285                 (&claim_txn[1], &claim_txn[2])
1286         } else {
1287                 (&claim_txn[2], &claim_txn[1])
1288         };
1289
1290         assert_eq!(preimage_tx.input.len(), 1);
1291         assert_eq!(preimage_bump_tx.input.len(), 1);
1292
1293         assert_eq!(preimage_tx.input.len(), 1);
1294         assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1295         assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1296
1297         assert_eq!(timeout_tx.input.len(), 1);
1298         assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1299         check_spends!(timeout_tx, remote_txn[0]);
1300         assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1301
1302         let events = nodes[0].node.get_and_clear_pending_msg_events();
1303         assert_eq!(events.len(), 3);
1304         for e in events {
1305                 match e {
1306                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1307                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1308                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1309                                 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1310                         },
1311                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
1312                                 assert!(update_add_htlcs.is_empty());
1313                                 assert!(update_fail_htlcs.is_empty());
1314                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1315                                 assert!(update_fail_malformed_htlcs.is_empty());
1316                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1317                         },
1318                         _ => panic!("Unexpected event"),
1319                 }
1320         }
1321 }
1322
1323 #[test]
1324 fn test_basic_channel_reserve() {
1325         let chanmon_cfgs = create_chanmon_cfgs(2);
1326         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1327         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1328         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1329         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1330
1331         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1332         let channel_reserve = chan_stat.channel_reserve_msat;
1333
1334         // The 2* and +1 are for the fee spike reserve.
1335         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], nodes[1], chan.2), 1 + 1, get_opt_anchors!(nodes[0], nodes[1], chan.2));
1336         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1337         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1338         let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1339         match err {
1340                 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1341                         match &fails[0] {
1342                                 &APIError::ChannelUnavailable{ref err} =>
1343                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1344                                 _ => panic!("Unexpected error variant"),
1345                         }
1346                 },
1347                 _ => panic!("Unexpected error variant"),
1348         }
1349         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1350         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put our balance under counterparty-announced channel reserve value", 1);
1351
1352         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1353 }
1354
1355 #[test]
1356 fn test_fee_spike_violation_fails_htlc() {
1357         let chanmon_cfgs = create_chanmon_cfgs(2);
1358         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1359         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1360         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1361         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1362
1363         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1364         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1365         let secp_ctx = Secp256k1::new();
1366         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1367
1368         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1369
1370         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1371         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1372         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1373         let msg = msgs::UpdateAddHTLC {
1374                 channel_id: chan.2,
1375                 htlc_id: 0,
1376                 amount_msat: htlc_msat,
1377                 payment_hash: payment_hash,
1378                 cltv_expiry: htlc_cltv,
1379                 onion_routing_packet: onion_packet,
1380         };
1381
1382         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1383
1384         // Now manually create the commitment_signed message corresponding to the update_add
1385         // nodes[0] just sent. In the code for construction of this message, "local" refers
1386         // to the sender of the message, and "remote" refers to the receiver.
1387
1388         let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1389
1390         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1391
1392         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1393         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1394         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1395                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1396                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1397                 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1398                 let chan_signer = local_chan.get_signer();
1399                 // Make the signer believe we validated another commitment, so we can release the secret
1400                 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1401
1402                 let pubkeys = chan_signer.pubkeys();
1403                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1404                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1405                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1406                  chan_signer.pubkeys().funding_pubkey)
1407         };
1408         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1409                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1410                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1411                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1412                 let chan_signer = remote_chan.get_signer();
1413                 let pubkeys = chan_signer.pubkeys();
1414                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1415                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1416                  chan_signer.pubkeys().funding_pubkey)
1417         };
1418
1419         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1420         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1421                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1422
1423         // Build the remote commitment transaction so we can sign it, and then later use the
1424         // signature for the commitment_signed message.
1425         let local_chan_balance = 1313;
1426
1427         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1428                 offered: false,
1429                 amount_msat: 3460001,
1430                 cltv_expiry: htlc_cltv,
1431                 payment_hash,
1432                 transaction_output_index: Some(1),
1433         };
1434
1435         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1436
1437         let res = {
1438                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1439                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1440                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
1441                 let local_chan_signer = local_chan.get_signer();
1442                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1443                         commitment_number,
1444                         95000,
1445                         local_chan_balance,
1446                         local_chan.opt_anchors(), local_funding, remote_funding,
1447                         commit_tx_keys.clone(),
1448                         feerate_per_kw,
1449                         &mut vec![(accepted_htlc_info, ())],
1450                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1451                 );
1452                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1453         };
1454
1455         let commit_signed_msg = msgs::CommitmentSigned {
1456                 channel_id: chan.2,
1457                 signature: res.0,
1458                 htlc_signatures: res.1
1459         };
1460
1461         // Send the commitment_signed message to the nodes[1].
1462         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1463         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1464
1465         // Send the RAA to nodes[1].
1466         let raa_msg = msgs::RevokeAndACK {
1467                 channel_id: chan.2,
1468                 per_commitment_secret: local_secret,
1469                 next_per_commitment_point: next_local_point
1470         };
1471         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1472
1473         let events = nodes[1].node.get_and_clear_pending_msg_events();
1474         assert_eq!(events.len(), 1);
1475         // Make sure the HTLC failed in the way we expect.
1476         match events[0] {
1477                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1478                         assert_eq!(update_fail_htlcs.len(), 1);
1479                         update_fail_htlcs[0].clone()
1480                 },
1481                 _ => panic!("Unexpected event"),
1482         };
1483         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1484                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1485
1486         check_added_monitors!(nodes[1], 2);
1487 }
1488
1489 #[test]
1490 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1491         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1492         // Set the fee rate for the channel very high, to the point where the fundee
1493         // sending any above-dust amount would result in a channel reserve violation.
1494         // In this test we check that we would be prevented from sending an HTLC in
1495         // this situation.
1496         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1497         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1498         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1499         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1500         let default_config = UserConfig::default();
1501         let opt_anchors = false;
1502
1503         let mut push_amt = 100_000_000;
1504         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1505
1506         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1507
1508         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1509
1510         // Sending exactly enough to hit the reserve amount should be accepted
1511         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1512                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1513         }
1514
1515         // However one more HTLC should be significantly over the reserve amount and fail.
1516         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1517         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
1518                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1519         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1520         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put counterparty balance under holder-announced channel reserve value".to_string(), 1);
1521 }
1522
1523 #[test]
1524 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1525         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1526         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1527         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1528         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1529         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1530         let default_config = UserConfig::default();
1531         let opt_anchors = false;
1532
1533         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1534         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1535         // transaction fee with 0 HTLCs (183 sats)).
1536         let mut push_amt = 100_000_000;
1537         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1538         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1539         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1540
1541         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1542         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1543                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1544         }
1545
1546         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1547         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1548         let secp_ctx = Secp256k1::new();
1549         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1550         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1551         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1552         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1553         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1554         let msg = msgs::UpdateAddHTLC {
1555                 channel_id: chan.2,
1556                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1557                 amount_msat: htlc_msat,
1558                 payment_hash: payment_hash,
1559                 cltv_expiry: htlc_cltv,
1560                 onion_routing_packet: onion_packet,
1561         };
1562
1563         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1564         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1565         nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1566         assert_eq!(nodes[0].node.list_channels().len(), 0);
1567         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1568         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1569         check_added_monitors!(nodes[0], 1);
1570         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string() });
1571 }
1572
1573 #[test]
1574 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1575         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1576         // calculating our commitment transaction fee (this was previously broken).
1577         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1578         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1579
1580         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1581         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1582         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1583         let default_config = UserConfig::default();
1584         let opt_anchors = false;
1585
1586         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1587         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1588         // transaction fee with 0 HTLCs (183 sats)).
1589         let mut push_amt = 100_000_000;
1590         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1591         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1592         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1593
1594         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1595                 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1596         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1597         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1598         // commitment transaction fee.
1599         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1600
1601         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1602         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1603                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1604         }
1605
1606         // One more than the dust amt should fail, however.
1607         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1608         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
1609                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1610 }
1611
1612 #[test]
1613 fn test_chan_init_feerate_unaffordability() {
1614         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1615         // channel reserve and feerate requirements.
1616         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1617         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1618         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1619         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1620         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1621         let default_config = UserConfig::default();
1622         let opt_anchors = false;
1623
1624         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1625         // HTLC.
1626         let mut push_amt = 100_000_000;
1627         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1628         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1629                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1630
1631         // During open, we don't have a "counterparty channel reserve" to check against, so that
1632         // requirement only comes into play on the open_channel handling side.
1633         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1634         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1635         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1636         open_channel_msg.push_msat += 1;
1637         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1638
1639         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1640         assert_eq!(msg_events.len(), 1);
1641         match msg_events[0] {
1642                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1643                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1644                 },
1645                 _ => panic!("Unexpected event"),
1646         }
1647 }
1648
1649 #[test]
1650 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1651         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1652         // calculating our counterparty's commitment transaction fee (this was previously broken).
1653         let chanmon_cfgs = create_chanmon_cfgs(2);
1654         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1655         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1656         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1657         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1658
1659         let payment_amt = 46000; // Dust amount
1660         // In the previous code, these first four payments would succeed.
1661         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1662         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1663         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1664         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1665
1666         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1667         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1668         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1669         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1670         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1671         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1672
1673         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1674         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1675         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1676         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1677 }
1678
1679 #[test]
1680 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1681         let chanmon_cfgs = create_chanmon_cfgs(3);
1682         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1683         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1684         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1685         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1686         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1687
1688         let feemsat = 239;
1689         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1690         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1691         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1692         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
1693
1694         // Add a 2* and +1 for the fee spike reserve.
1695         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1696         let recv_value_1 = (chan_stat.value_to_self_msat - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlc)/2;
1697         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1698
1699         // Add a pending HTLC.
1700         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1701         let payment_event_1 = {
1702                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1703                 check_added_monitors!(nodes[0], 1);
1704
1705                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1706                 assert_eq!(events.len(), 1);
1707                 SendEvent::from_event(events.remove(0))
1708         };
1709         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1710
1711         // Attempt to trigger a channel reserve violation --> payment failure.
1712         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1713         let recv_value_2 = chan_stat.value_to_self_msat - amt_msat_1 - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlcs + 1;
1714         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1715         let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1716
1717         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1718         let secp_ctx = Secp256k1::new();
1719         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1720         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1721         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1722         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1723         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1724         let msg = msgs::UpdateAddHTLC {
1725                 channel_id: chan.2,
1726                 htlc_id: 1,
1727                 amount_msat: htlc_msat + 1,
1728                 payment_hash: our_payment_hash_1,
1729                 cltv_expiry: htlc_cltv,
1730                 onion_routing_packet: onion_packet,
1731         };
1732
1733         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1734         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1735         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1736         assert_eq!(nodes[1].node.list_channels().len(), 1);
1737         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1738         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1739         check_added_monitors!(nodes[1], 1);
1740         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1741 }
1742
1743 #[test]
1744 fn test_inbound_outbound_capacity_is_not_zero() {
1745         let chanmon_cfgs = create_chanmon_cfgs(2);
1746         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1747         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1748         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1749         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1750         let channels0 = node_chanmgrs[0].list_channels();
1751         let channels1 = node_chanmgrs[1].list_channels();
1752         let default_config = UserConfig::default();
1753         assert_eq!(channels0.len(), 1);
1754         assert_eq!(channels1.len(), 1);
1755
1756         let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1757         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1758         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1759
1760         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1761         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1762 }
1763
1764 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1765         (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1766 }
1767
1768 #[test]
1769 fn test_channel_reserve_holding_cell_htlcs() {
1770         let chanmon_cfgs = create_chanmon_cfgs(3);
1771         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1772         // When this test was written, the default base fee floated based on the HTLC count.
1773         // It is now fixed, so we simply set the fee to the expected value here.
1774         let mut config = test_default_channel_config();
1775         config.channel_config.forwarding_fee_base_msat = 239;
1776         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1777         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1778         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1779         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1780
1781         let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1782         let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1783
1784         let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1785         let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1786
1787         macro_rules! expect_forward {
1788                 ($node: expr) => {{
1789                         let mut events = $node.node.get_and_clear_pending_msg_events();
1790                         assert_eq!(events.len(), 1);
1791                         check_added_monitors!($node, 1);
1792                         let payment_event = SendEvent::from_event(events.remove(0));
1793                         payment_event
1794                 }}
1795         }
1796
1797         let feemsat = 239; // set above
1798         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1799         let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1800         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_1.2);
1801
1802         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1803
1804         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1805         {
1806                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1807                         .with_features(nodes[2].node.invoice_features()).with_max_channel_saturation_power_of_half(0);
1808                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0, TEST_FINAL_CLTV);
1809                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1810                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1811
1812                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
1813                         assert!(regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap().is_match(err)));
1814                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1815                 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put us over the max HTLC value in flight our peer will accept", 1);
1816         }
1817
1818         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1819         // nodes[0]'s wealth
1820         loop {
1821                 let amt_msat = recv_value_0 + total_fee_msat;
1822                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1823                 // Also, ensure that each payment has enough to be over the dust limit to
1824                 // ensure it'll be included in each commit tx fee calculation.
1825                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1826                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1827                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1828                         break;
1829                 }
1830
1831                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1832                         .with_features(nodes[2].node.invoice_features()).with_max_channel_saturation_power_of_half(0);
1833                 let route = get_route!(nodes[0], payment_params, recv_value_0, TEST_FINAL_CLTV).unwrap();
1834                 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1835                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1836
1837                 let (stat01_, stat11_, stat12_, stat22_) = (
1838                         get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1839                         get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1840                         get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1841                         get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1842                 );
1843
1844                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1845                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1846                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1847                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1848                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1849         }
1850
1851         // adding pending output.
1852         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1853         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1854         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1855         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1856         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1857         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1858         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1859         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1860         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1861         // policy.
1862         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1863         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1864         let amt_msat_1 = recv_value_1 + total_fee_msat;
1865
1866         let (route_1, our_payment_hash_1, our_payment_preimage_1, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_1);
1867         let payment_event_1 = {
1868                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1869                 check_added_monitors!(nodes[0], 1);
1870
1871                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1872                 assert_eq!(events.len(), 1);
1873                 SendEvent::from_event(events.remove(0))
1874         };
1875         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1876
1877         // channel reserve test with htlc pending output > 0
1878         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1879         {
1880                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1881                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
1882                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1883                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1884         }
1885
1886         // split the rest to test holding cell
1887         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1888         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1889         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1890         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1891         {
1892                 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1893                 assert_eq!(stat.value_to_self_msat - (stat.pending_outbound_htlcs_amount_msat + recv_value_21 + recv_value_22 + total_fee_msat + total_fee_msat + commit_tx_fee_3_htlcs), stat.channel_reserve_msat);
1894         }
1895
1896         // now see if they go through on both sides
1897         let (route_21, our_payment_hash_21, our_payment_preimage_21, our_payment_secret_21) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_21);
1898         // but this will stuck in the holding cell
1899         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1900         check_added_monitors!(nodes[0], 0);
1901         let events = nodes[0].node.get_and_clear_pending_events();
1902         assert_eq!(events.len(), 0);
1903
1904         // test with outbound holding cell amount > 0
1905         {
1906                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1907                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
1908                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1909                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1910                 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put our balance under counterparty-announced channel reserve value", 2);
1911         }
1912
1913         let (route_22, our_payment_hash_22, our_payment_preimage_22, our_payment_secret_22) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1914         // this will also stuck in the holding cell
1915         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1916         check_added_monitors!(nodes[0], 0);
1917         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1918         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1919
1920         // flush the pending htlc
1921         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1922         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1923         check_added_monitors!(nodes[1], 1);
1924
1925         // the pending htlc should be promoted to committed
1926         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1927         check_added_monitors!(nodes[0], 1);
1928         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1929
1930         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1931         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1932         // No commitment_signed so get_event_msg's assert(len == 1) passes
1933         check_added_monitors!(nodes[0], 1);
1934
1935         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1936         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1937         check_added_monitors!(nodes[1], 1);
1938
1939         expect_pending_htlcs_forwardable!(nodes[1]);
1940
1941         let ref payment_event_11 = expect_forward!(nodes[1]);
1942         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1943         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1944
1945         expect_pending_htlcs_forwardable!(nodes[2]);
1946         expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1947
1948         // flush the htlcs in the holding cell
1949         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1950         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1951         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1952         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1953         expect_pending_htlcs_forwardable!(nodes[1]);
1954
1955         let ref payment_event_3 = expect_forward!(nodes[1]);
1956         assert_eq!(payment_event_3.msgs.len(), 2);
1957         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1958         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1959
1960         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1961         expect_pending_htlcs_forwardable!(nodes[2]);
1962
1963         let events = nodes[2].node.get_and_clear_pending_events();
1964         assert_eq!(events.len(), 2);
1965         match events[0] {
1966                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
1967                         assert_eq!(our_payment_hash_21, *payment_hash);
1968                         assert_eq!(recv_value_21, amount_msat);
1969                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
1970                         assert_eq!(via_channel_id, Some(chan_2.2));
1971                         match &purpose {
1972                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1973                                         assert!(payment_preimage.is_none());
1974                                         assert_eq!(our_payment_secret_21, *payment_secret);
1975                                 },
1976                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1977                         }
1978                 },
1979                 _ => panic!("Unexpected event"),
1980         }
1981         match events[1] {
1982                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
1983                         assert_eq!(our_payment_hash_22, *payment_hash);
1984                         assert_eq!(recv_value_22, amount_msat);
1985                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
1986                         assert_eq!(via_channel_id, Some(chan_2.2));
1987                         match &purpose {
1988                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1989                                         assert!(payment_preimage.is_none());
1990                                         assert_eq!(our_payment_secret_22, *payment_secret);
1991                                 },
1992                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1993                         }
1994                 },
1995                 _ => panic!("Unexpected event"),
1996         }
1997
1998         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1999         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2000         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2001
2002         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2003         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2004         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2005
2006         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2007         let expected_value_to_self = stat01.value_to_self_msat - (recv_value_1 + total_fee_msat) - (recv_value_21 + total_fee_msat) - (recv_value_22 + total_fee_msat) - (recv_value_3 + total_fee_msat);
2008         let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2009         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2010         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2011
2012         let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2013         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2014 }
2015
2016 #[test]
2017 fn channel_reserve_in_flight_removes() {
2018         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2019         // can send to its counterparty, but due to update ordering, the other side may not yet have
2020         // considered those HTLCs fully removed.
2021         // This tests that we don't count HTLCs which will not be included in the next remote
2022         // commitment transaction towards the reserve value (as it implies no commitment transaction
2023         // will be generated which violates the remote reserve value).
2024         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2025         // To test this we:
2026         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2027         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2028         //    you only consider the value of the first HTLC, it may not),
2029         //  * start routing a third HTLC from A to B,
2030         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2031         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2032         //  * deliver the first fulfill from B
2033         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2034         //    claim,
2035         //  * deliver A's response CS and RAA.
2036         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2037         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2038         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2039         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2040         let chanmon_cfgs = create_chanmon_cfgs(2);
2041         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2042         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2043         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2044         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2045
2046         let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2047         // Route the first two HTLCs.
2048         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2049         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2050         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2051
2052         // Start routing the third HTLC (this is just used to get everyone in the right state).
2053         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2054         let send_1 = {
2055                 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2056                 check_added_monitors!(nodes[0], 1);
2057                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2058                 assert_eq!(events.len(), 1);
2059                 SendEvent::from_event(events.remove(0))
2060         };
2061
2062         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2063         // initial fulfill/CS.
2064         nodes[1].node.claim_funds(payment_preimage_1);
2065         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2066         check_added_monitors!(nodes[1], 1);
2067         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2068
2069         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2070         // remove the second HTLC when we send the HTLC back from B to A.
2071         nodes[1].node.claim_funds(payment_preimage_2);
2072         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2073         check_added_monitors!(nodes[1], 1);
2074         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2075
2076         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2077         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2078         check_added_monitors!(nodes[0], 1);
2079         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2080         expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2081
2082         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2083         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2084         check_added_monitors!(nodes[1], 1);
2085         // B is already AwaitingRAA, so cant generate a CS here
2086         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2087
2088         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2089         check_added_monitors!(nodes[1], 1);
2090         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2091
2092         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2093         check_added_monitors!(nodes[0], 1);
2094         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2095
2096         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2097         check_added_monitors!(nodes[1], 1);
2098         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2099
2100         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2101         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2102         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2103         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2104         // on-chain as necessary).
2105         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2106         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2107         check_added_monitors!(nodes[0], 1);
2108         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2109         expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2110
2111         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2112         check_added_monitors!(nodes[1], 1);
2113         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2114
2115         expect_pending_htlcs_forwardable!(nodes[1]);
2116         expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2117
2118         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2119         // resolve the second HTLC from A's point of view.
2120         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2121         check_added_monitors!(nodes[0], 1);
2122         expect_payment_path_successful!(nodes[0]);
2123         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2124
2125         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2126         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2127         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2128         let send_2 = {
2129                 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2130                 check_added_monitors!(nodes[1], 1);
2131                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2132                 assert_eq!(events.len(), 1);
2133                 SendEvent::from_event(events.remove(0))
2134         };
2135
2136         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2137         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2138         check_added_monitors!(nodes[0], 1);
2139         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2140
2141         // Now just resolve all the outstanding messages/HTLCs for completeness...
2142
2143         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2144         check_added_monitors!(nodes[1], 1);
2145         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2146
2147         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2148         check_added_monitors!(nodes[1], 1);
2149
2150         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2151         check_added_monitors!(nodes[0], 1);
2152         expect_payment_path_successful!(nodes[0]);
2153         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2154
2155         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2156         check_added_monitors!(nodes[1], 1);
2157         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2158
2159         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2160         check_added_monitors!(nodes[0], 1);
2161
2162         expect_pending_htlcs_forwardable!(nodes[0]);
2163         expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2164
2165         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2166         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2167 }
2168
2169 #[test]
2170 fn channel_monitor_network_test() {
2171         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2172         // tests that ChannelMonitor is able to recover from various states.
2173         let chanmon_cfgs = create_chanmon_cfgs(5);
2174         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2175         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2176         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2177
2178         // Create some initial channels
2179         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2180         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2181         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2182         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2183
2184         // Make sure all nodes are at the same starting height
2185         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2186         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2187         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2188         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2189         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2190
2191         // Rebalance the network a bit by relaying one payment through all the channels...
2192         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2193         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2194         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2195         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2196
2197         // Simple case with no pending HTLCs:
2198         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2199         check_added_monitors!(nodes[1], 1);
2200         check_closed_broadcast!(nodes[1], true);
2201         {
2202                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2203                 assert_eq!(node_txn.len(), 1);
2204                 mine_transaction(&nodes[0], &node_txn[0]);
2205                 check_added_monitors!(nodes[0], 1);
2206                 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2207         }
2208         check_closed_broadcast!(nodes[0], true);
2209         assert_eq!(nodes[0].node.list_channels().len(), 0);
2210         assert_eq!(nodes[1].node.list_channels().len(), 1);
2211         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2212         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2213
2214         // One pending HTLC is discarded by the force-close:
2215         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2216
2217         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2218         // broadcasted until we reach the timelock time).
2219         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2220         check_closed_broadcast!(nodes[1], true);
2221         check_added_monitors!(nodes[1], 1);
2222         {
2223                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2224                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2225                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2226                 mine_transaction(&nodes[2], &node_txn[0]);
2227                 check_added_monitors!(nodes[2], 1);
2228                 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2229         }
2230         check_closed_broadcast!(nodes[2], true);
2231         assert_eq!(nodes[1].node.list_channels().len(), 0);
2232         assert_eq!(nodes[2].node.list_channels().len(), 1);
2233         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2234         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2235
2236         macro_rules! claim_funds {
2237                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2238                         {
2239                                 $node.node.claim_funds($preimage);
2240                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2241                                 check_added_monitors!($node, 1);
2242
2243                                 let events = $node.node.get_and_clear_pending_msg_events();
2244                                 assert_eq!(events.len(), 1);
2245                                 match events[0] {
2246                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2247                                                 assert!(update_add_htlcs.is_empty());
2248                                                 assert!(update_fail_htlcs.is_empty());
2249                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2250                                         },
2251                                         _ => panic!("Unexpected event"),
2252                                 };
2253                         }
2254                 }
2255         }
2256
2257         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2258         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2259         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2260         check_added_monitors!(nodes[2], 1);
2261         check_closed_broadcast!(nodes[2], true);
2262         let node2_commitment_txid;
2263         {
2264                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2265                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2266                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2267                 node2_commitment_txid = node_txn[0].txid();
2268
2269                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2270                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2271                 mine_transaction(&nodes[3], &node_txn[0]);
2272                 check_added_monitors!(nodes[3], 1);
2273                 check_preimage_claim(&nodes[3], &node_txn);
2274         }
2275         check_closed_broadcast!(nodes[3], true);
2276         assert_eq!(nodes[2].node.list_channels().len(), 0);
2277         assert_eq!(nodes[3].node.list_channels().len(), 1);
2278         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2279         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2280
2281         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2282         // confusing us in the following tests.
2283         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2284
2285         // One pending HTLC to time out:
2286         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2287         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2288         // buffer space).
2289
2290         let (close_chan_update_1, close_chan_update_2) = {
2291                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2292                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2293                 assert_eq!(events.len(), 2);
2294                 let close_chan_update_1 = match events[0] {
2295                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2296                                 msg.clone()
2297                         },
2298                         _ => panic!("Unexpected event"),
2299                 };
2300                 match events[1] {
2301                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2302                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2303                         },
2304                         _ => panic!("Unexpected event"),
2305                 }
2306                 check_added_monitors!(nodes[3], 1);
2307
2308                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2309                 {
2310                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2311                         node_txn.retain(|tx| {
2312                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2313                                         false
2314                                 } else { true }
2315                         });
2316                 }
2317
2318                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2319
2320                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2321                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2322
2323                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2324                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2325                 assert_eq!(events.len(), 2);
2326                 let close_chan_update_2 = match events[0] {
2327                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2328                                 msg.clone()
2329                         },
2330                         _ => panic!("Unexpected event"),
2331                 };
2332                 match events[1] {
2333                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2334                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2335                         },
2336                         _ => panic!("Unexpected event"),
2337                 }
2338                 check_added_monitors!(nodes[4], 1);
2339                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2340
2341                 mine_transaction(&nodes[4], &node_txn[0]);
2342                 check_preimage_claim(&nodes[4], &node_txn);
2343                 (close_chan_update_1, close_chan_update_2)
2344         };
2345         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2346         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2347         assert_eq!(nodes[3].node.list_channels().len(), 0);
2348         assert_eq!(nodes[4].node.list_channels().len(), 0);
2349
2350         assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2351                 ChannelMonitorUpdateStatus::Completed);
2352         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2353         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2354 }
2355
2356 #[test]
2357 fn test_justice_tx() {
2358         // Test justice txn built on revoked HTLC-Success tx, against both sides
2359         let mut alice_config = UserConfig::default();
2360         alice_config.channel_handshake_config.announced_channel = true;
2361         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2362         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2363         let mut bob_config = UserConfig::default();
2364         bob_config.channel_handshake_config.announced_channel = true;
2365         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2366         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2367         let user_cfgs = [Some(alice_config), Some(bob_config)];
2368         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2369         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2370         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2371         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2372         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2373         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2374         *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2375         // Create some new channels:
2376         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2377
2378         // A pending HTLC which will be revoked:
2379         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2380         // Get the will-be-revoked local txn from nodes[0]
2381         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2382         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2383         assert_eq!(revoked_local_txn[0].input.len(), 1);
2384         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2385         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2386         assert_eq!(revoked_local_txn[1].input.len(), 1);
2387         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2388         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2389         // Revoke the old state
2390         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2391
2392         {
2393                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2394                 {
2395                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2396                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2397                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2398
2399                         check_spends!(node_txn[0], revoked_local_txn[0]);
2400                         node_txn.swap_remove(0);
2401                 }
2402                 check_added_monitors!(nodes[1], 1);
2403                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2404                 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2405
2406                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2407                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2408                 // Verify broadcast of revoked HTLC-timeout
2409                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2410                 check_added_monitors!(nodes[0], 1);
2411                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2412                 // Broadcast revoked HTLC-timeout on node 1
2413                 mine_transaction(&nodes[1], &node_txn[1]);
2414                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2415         }
2416         get_announce_close_broadcast_events(&nodes, 0, 1);
2417
2418         assert_eq!(nodes[0].node.list_channels().len(), 0);
2419         assert_eq!(nodes[1].node.list_channels().len(), 0);
2420
2421         // We test justice_tx build by A on B's revoked HTLC-Success tx
2422         // Create some new channels:
2423         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2424         {
2425                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2426                 node_txn.clear();
2427         }
2428
2429         // A pending HTLC which will be revoked:
2430         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2431         // Get the will-be-revoked local txn from B
2432         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2433         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2434         assert_eq!(revoked_local_txn[0].input.len(), 1);
2435         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2436         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2437         // Revoke the old state
2438         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2439         {
2440                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2441                 {
2442                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2443                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2444                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2445
2446                         check_spends!(node_txn[0], revoked_local_txn[0]);
2447                         node_txn.swap_remove(0);
2448                 }
2449                 check_added_monitors!(nodes[0], 1);
2450                 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2451
2452                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2453                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2454                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2455                 check_added_monitors!(nodes[1], 1);
2456                 mine_transaction(&nodes[0], &node_txn[1]);
2457                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2458                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2459         }
2460         get_announce_close_broadcast_events(&nodes, 0, 1);
2461         assert_eq!(nodes[0].node.list_channels().len(), 0);
2462         assert_eq!(nodes[1].node.list_channels().len(), 0);
2463 }
2464
2465 #[test]
2466 fn revoked_output_claim() {
2467         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2468         // transaction is broadcast by its counterparty
2469         let chanmon_cfgs = create_chanmon_cfgs(2);
2470         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2471         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2472         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2473         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2474         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2475         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2476         assert_eq!(revoked_local_txn.len(), 1);
2477         // Only output is the full channel value back to nodes[0]:
2478         assert_eq!(revoked_local_txn[0].output.len(), 1);
2479         // Send a payment through, updating everyone's latest commitment txn
2480         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2481
2482         // Inform nodes[1] that nodes[0] broadcast a stale tx
2483         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2484         check_added_monitors!(nodes[1], 1);
2485         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2486         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2487         assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2488
2489         check_spends!(node_txn[0], revoked_local_txn[0]);
2490
2491         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2492         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2493         get_announce_close_broadcast_events(&nodes, 0, 1);
2494         check_added_monitors!(nodes[0], 1);
2495         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2496 }
2497
2498 #[test]
2499 fn claim_htlc_outputs_shared_tx() {
2500         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2501         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2502         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2503         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2504         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2505         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2506
2507         // Create some new channel:
2508         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2509
2510         // Rebalance the network to generate htlc in the two directions
2511         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2512         // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx
2513         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2514         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2515
2516         // Get the will-be-revoked local txn from node[0]
2517         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2518         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2519         assert_eq!(revoked_local_txn[0].input.len(), 1);
2520         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2521         assert_eq!(revoked_local_txn[1].input.len(), 1);
2522         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2523         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2524         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2525
2526         //Revoke the old state
2527         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2528
2529         {
2530                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2531                 check_added_monitors!(nodes[0], 1);
2532                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2533                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2534                 check_added_monitors!(nodes[1], 1);
2535                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2536                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2537                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2538
2539                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2540                 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2541
2542                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2543                 check_spends!(node_txn[0], revoked_local_txn[0]);
2544
2545                 let mut witness_lens = BTreeSet::new();
2546                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2547                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2548                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2549                 assert_eq!(witness_lens.len(), 3);
2550                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2551                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2552                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2553
2554                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2555                 // ANTI_REORG_DELAY confirmations.
2556                 mine_transaction(&nodes[1], &node_txn[0]);
2557                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2558                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2559         }
2560         get_announce_close_broadcast_events(&nodes, 0, 1);
2561         assert_eq!(nodes[0].node.list_channels().len(), 0);
2562         assert_eq!(nodes[1].node.list_channels().len(), 0);
2563 }
2564
2565 #[test]
2566 fn claim_htlc_outputs_single_tx() {
2567         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2568         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2569         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2570         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2571         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2572         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2573
2574         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2575
2576         // Rebalance the network to generate htlc in the two directions
2577         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2578         // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx, but this
2579         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2580         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2581         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2582
2583         // Get the will-be-revoked local txn from node[0]
2584         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2585
2586         //Revoke the old state
2587         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2588
2589         {
2590                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2591                 check_added_monitors!(nodes[0], 1);
2592                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2593                 check_added_monitors!(nodes[1], 1);
2594                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2595                 let mut events = nodes[0].node.get_and_clear_pending_events();
2596                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2597                 match events.last().unwrap() {
2598                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2599                         _ => panic!("Unexpected event"),
2600                 }
2601
2602                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2603                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2604
2605                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2606                 assert_eq!(node_txn.len(), 7);
2607
2608                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2609                 assert_eq!(node_txn[0].input.len(), 1);
2610                 check_spends!(node_txn[0], chan_1.3);
2611                 assert_eq!(node_txn[1].input.len(), 1);
2612                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2613                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2614                 check_spends!(node_txn[1], node_txn[0]);
2615
2616                 // Justice transactions are indices 2-3-4
2617                 assert_eq!(node_txn[2].input.len(), 1);
2618                 assert_eq!(node_txn[3].input.len(), 1);
2619                 assert_eq!(node_txn[4].input.len(), 1);
2620
2621                 check_spends!(node_txn[2], revoked_local_txn[0]);
2622                 check_spends!(node_txn[3], revoked_local_txn[0]);
2623                 check_spends!(node_txn[4], revoked_local_txn[0]);
2624
2625                 let mut witness_lens = BTreeSet::new();
2626                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2627                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2628                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2629                 assert_eq!(witness_lens.len(), 3);
2630                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2631                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2632                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2633
2634                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2635                 // ANTI_REORG_DELAY confirmations.
2636                 mine_transaction(&nodes[1], &node_txn[2]);
2637                 mine_transaction(&nodes[1], &node_txn[3]);
2638                 mine_transaction(&nodes[1], &node_txn[4]);
2639                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2640                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2641         }
2642         get_announce_close_broadcast_events(&nodes, 0, 1);
2643         assert_eq!(nodes[0].node.list_channels().len(), 0);
2644         assert_eq!(nodes[1].node.list_channels().len(), 0);
2645 }
2646
2647 #[test]
2648 fn test_htlc_on_chain_success() {
2649         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2650         // the preimage backward accordingly. So here we test that ChannelManager is
2651         // broadcasting the right event to other nodes in payment path.
2652         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2653         // A --------------------> B ----------------------> C (preimage)
2654         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2655         // commitment transaction was broadcast.
2656         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2657         // towards B.
2658         // B should be able to claim via preimage if A then broadcasts its local tx.
2659         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2660         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2661         // PaymentSent event).
2662
2663         let chanmon_cfgs = create_chanmon_cfgs(3);
2664         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2665         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2666         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2667
2668         // Create some initial channels
2669         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2670         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2671
2672         // Ensure all nodes are at the same height
2673         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2674         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2675         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2676         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2677
2678         // Rebalance the network a bit by relaying one payment through all the channels...
2679         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2680         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2681
2682         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2683         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2684
2685         // Broadcast legit commitment tx from C on B's chain
2686         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2687         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2688         assert_eq!(commitment_tx.len(), 1);
2689         check_spends!(commitment_tx[0], chan_2.3);
2690         nodes[2].node.claim_funds(our_payment_preimage);
2691         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2692         nodes[2].node.claim_funds(our_payment_preimage_2);
2693         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2694         check_added_monitors!(nodes[2], 2);
2695         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2696         assert!(updates.update_add_htlcs.is_empty());
2697         assert!(updates.update_fail_htlcs.is_empty());
2698         assert!(updates.update_fail_malformed_htlcs.is_empty());
2699         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2700
2701         mine_transaction(&nodes[2], &commitment_tx[0]);
2702         check_closed_broadcast!(nodes[2], true);
2703         check_added_monitors!(nodes[2], 1);
2704         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2705         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2706         assert_eq!(node_txn.len(), 2);
2707         check_spends!(node_txn[0], commitment_tx[0]);
2708         check_spends!(node_txn[1], commitment_tx[0]);
2709         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2710         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2711         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2712         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2713         assert_eq!(node_txn[0].lock_time.0, 0);
2714         assert_eq!(node_txn[1].lock_time.0, 0);
2715
2716         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2717         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2718         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone(), node_txn[1].clone()]});
2719         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2720         {
2721                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2722                 assert_eq!(added_monitors.len(), 1);
2723                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2724                 added_monitors.clear();
2725         }
2726         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2727         assert_eq!(forwarded_events.len(), 3);
2728         match forwarded_events[0] {
2729                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2730                 _ => panic!("Unexpected event"),
2731         }
2732         let chan_id = Some(chan_1.2);
2733         match forwarded_events[1] {
2734                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
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 mut 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
2761         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2762         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2763
2764         match nodes_2_event {
2765                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2766                 _ => panic!("Unexpected event"),
2767         }
2768
2769         match nodes_0_event {
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
2780         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2781         match events[0] {
2782                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2783                 _ => panic!("Unexpected event"),
2784         }
2785
2786         macro_rules! check_tx_local_broadcast {
2787                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2788                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2789                         assert_eq!(node_txn.len(), 2);
2790                         // Node[1]: 2 * HTLC-timeout tx
2791                         // Node[0]: 2 * HTLC-timeout tx
2792                         check_spends!(node_txn[0], $commitment_tx);
2793                         check_spends!(node_txn[1], $commitment_tx);
2794                         assert_ne!(node_txn[0].lock_time.0, 0);
2795                         assert_ne!(node_txn[1].lock_time.0, 0);
2796                         if $htlc_offered {
2797                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2798                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2799                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2800                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2801                         } else {
2802                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2803                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2804                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2805                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2806                         }
2807                         node_txn.clear();
2808                 } }
2809         }
2810         // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2811         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2812
2813         // Broadcast legit commitment tx from A on B's chain
2814         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2815         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2816         check_spends!(node_a_commitment_tx[0], chan_1.3);
2817         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2818         check_closed_broadcast!(nodes[1], true);
2819         check_added_monitors!(nodes[1], 1);
2820         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2821         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2822         assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2823         let commitment_spend =
2824                 if node_txn.len() == 1 {
2825                         &node_txn[0]
2826                 } else {
2827                         // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2828                         // FullBlockViaListen
2829                         if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2830                                 check_spends!(node_txn[1], commitment_tx[0]);
2831                                 check_spends!(node_txn[2], commitment_tx[0]);
2832                                 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2833                                 &node_txn[0]
2834                         } else {
2835                                 check_spends!(node_txn[0], commitment_tx[0]);
2836                                 check_spends!(node_txn[1], commitment_tx[0]);
2837                                 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2838                                 &node_txn[2]
2839                         }
2840                 };
2841
2842         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2843         assert_eq!(commitment_spend.input.len(), 2);
2844         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2845         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2846         assert_eq!(commitment_spend.lock_time.0, 0);
2847         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2848         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2849         // we already checked the same situation with A.
2850
2851         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2852         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2853         connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2854         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2855         check_closed_broadcast!(nodes[0], true);
2856         check_added_monitors!(nodes[0], 1);
2857         let events = nodes[0].node.get_and_clear_pending_events();
2858         assert_eq!(events.len(), 5);
2859         let mut first_claimed = false;
2860         for event in events {
2861                 match event {
2862                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2863                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2864                                         assert!(!first_claimed);
2865                                         first_claimed = true;
2866                                 } else {
2867                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2868                                         assert_eq!(payment_hash, payment_hash_2);
2869                                 }
2870                         },
2871                         Event::PaymentPathSuccessful { .. } => {},
2872                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2873                         _ => panic!("Unexpected event"),
2874                 }
2875         }
2876         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
2877 }
2878
2879 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2880         // Test that in case of a unilateral close onchain, we detect the state of output and
2881         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2882         // broadcasting the right event to other nodes in payment path.
2883         // A ------------------> B ----------------------> C (timeout)
2884         //    B's commitment tx                 C's commitment tx
2885         //            \                                  \
2886         //         B's HTLC timeout tx               B's timeout tx
2887
2888         let chanmon_cfgs = create_chanmon_cfgs(3);
2889         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2890         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2891         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2892         *nodes[0].connect_style.borrow_mut() = connect_style;
2893         *nodes[1].connect_style.borrow_mut() = connect_style;
2894         *nodes[2].connect_style.borrow_mut() = connect_style;
2895
2896         // Create some intial channels
2897         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2898         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2899
2900         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2901         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2902         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2903
2904         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2905
2906         // Broadcast legit commitment tx from C on B's chain
2907         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2908         check_spends!(commitment_tx[0], chan_2.3);
2909         nodes[2].node.fail_htlc_backwards(&payment_hash);
2910         check_added_monitors!(nodes[2], 0);
2911         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2912         check_added_monitors!(nodes[2], 1);
2913
2914         let events = nodes[2].node.get_and_clear_pending_msg_events();
2915         assert_eq!(events.len(), 1);
2916         match events[0] {
2917                 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, .. } } => {
2918                         assert!(update_add_htlcs.is_empty());
2919                         assert!(!update_fail_htlcs.is_empty());
2920                         assert!(update_fulfill_htlcs.is_empty());
2921                         assert!(update_fail_malformed_htlcs.is_empty());
2922                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2923                 },
2924                 _ => panic!("Unexpected event"),
2925         };
2926         mine_transaction(&nodes[2], &commitment_tx[0]);
2927         check_closed_broadcast!(nodes[2], true);
2928         check_added_monitors!(nodes[2], 1);
2929         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2930         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2931         assert_eq!(node_txn.len(), 0);
2932
2933         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2934         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2935         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2936         mine_transaction(&nodes[1], &commitment_tx[0]);
2937         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2938         let timeout_tx;
2939         {
2940                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2941                 assert_eq!(node_txn.len(), 3); // 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2942
2943                 check_spends!(node_txn[2], commitment_tx[0]);
2944                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2945
2946                 check_spends!(node_txn[0], chan_2.3);
2947                 check_spends!(node_txn[1], node_txn[0]);
2948                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2949                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2950
2951                 timeout_tx = node_txn[2].clone();
2952                 node_txn.clear();
2953         }
2954
2955         mine_transaction(&nodes[1], &timeout_tx);
2956         check_added_monitors!(nodes[1], 1);
2957         check_closed_broadcast!(nodes[1], true);
2958
2959         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2960
2961         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 }]);
2962         check_added_monitors!(nodes[1], 1);
2963         let events = nodes[1].node.get_and_clear_pending_msg_events();
2964         assert_eq!(events.len(), 1);
2965         match events[0] {
2966                 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, .. } } => {
2967                         assert!(update_add_htlcs.is_empty());
2968                         assert!(!update_fail_htlcs.is_empty());
2969                         assert!(update_fulfill_htlcs.is_empty());
2970                         assert!(update_fail_malformed_htlcs.is_empty());
2971                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2972                 },
2973                 _ => panic!("Unexpected event"),
2974         };
2975
2976         // Broadcast legit commitment tx from B on A's chain
2977         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2978         check_spends!(commitment_tx[0], chan_1.3);
2979
2980         mine_transaction(&nodes[0], &commitment_tx[0]);
2981         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2982
2983         check_closed_broadcast!(nodes[0], true);
2984         check_added_monitors!(nodes[0], 1);
2985         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2986         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
2987         assert_eq!(node_txn.len(), 1);
2988         check_spends!(node_txn[0], commitment_tx[0]);
2989         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2990 }
2991
2992 #[test]
2993 fn test_htlc_on_chain_timeout() {
2994         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
2995         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
2996         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
2997 }
2998
2999 #[test]
3000 fn test_simple_commitment_revoked_fail_backward() {
3001         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3002         // and fail backward accordingly.
3003
3004         let chanmon_cfgs = create_chanmon_cfgs(3);
3005         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3006         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3007         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3008
3009         // Create some initial channels
3010         create_announced_chan_between_nodes(&nodes, 0, 1);
3011         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3012
3013         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3014         // Get the will-be-revoked local txn from nodes[2]
3015         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3016         // Revoke the old state
3017         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3018
3019         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3020
3021         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3022         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3023         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3024         check_added_monitors!(nodes[1], 1);
3025         check_closed_broadcast!(nodes[1], true);
3026
3027         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 }]);
3028         check_added_monitors!(nodes[1], 1);
3029         let events = nodes[1].node.get_and_clear_pending_msg_events();
3030         assert_eq!(events.len(), 1);
3031         match events[0] {
3032                 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, .. } } => {
3033                         assert!(update_add_htlcs.is_empty());
3034                         assert_eq!(update_fail_htlcs.len(), 1);
3035                         assert!(update_fulfill_htlcs.is_empty());
3036                         assert!(update_fail_malformed_htlcs.is_empty());
3037                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3038
3039                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3040                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3041                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3042                 },
3043                 _ => panic!("Unexpected event"),
3044         }
3045 }
3046
3047 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3048         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3049         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3050         // commitment transaction anymore.
3051         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3052         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3053         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3054         // technically disallowed and we should probably handle it reasonably.
3055         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3056         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3057         // transactions:
3058         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3059         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3060         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3061         //   and once they revoke the previous commitment transaction (allowing us to send a new
3062         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3063         let chanmon_cfgs = create_chanmon_cfgs(3);
3064         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3065         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3066         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3067
3068         // Create some initial channels
3069         create_announced_chan_between_nodes(&nodes, 0, 1);
3070         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3071
3072         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 });
3073         // Get the will-be-revoked local txn from nodes[2]
3074         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3075         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3076         // Revoke the old state
3077         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3078
3079         let value = if use_dust {
3080                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3081                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3082                 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3083                         .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3084         } else { 3000000 };
3085
3086         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3087         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3088         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3089
3090         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3091         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3092         check_added_monitors!(nodes[2], 1);
3093         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3094         assert!(updates.update_add_htlcs.is_empty());
3095         assert!(updates.update_fulfill_htlcs.is_empty());
3096         assert!(updates.update_fail_malformed_htlcs.is_empty());
3097         assert_eq!(updates.update_fail_htlcs.len(), 1);
3098         assert!(updates.update_fee.is_none());
3099         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3100         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3101         // Drop the last RAA from 3 -> 2
3102
3103         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3104         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3105         check_added_monitors!(nodes[2], 1);
3106         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3107         assert!(updates.update_add_htlcs.is_empty());
3108         assert!(updates.update_fulfill_htlcs.is_empty());
3109         assert!(updates.update_fail_malformed_htlcs.is_empty());
3110         assert_eq!(updates.update_fail_htlcs.len(), 1);
3111         assert!(updates.update_fee.is_none());
3112         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3113         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3114         check_added_monitors!(nodes[1], 1);
3115         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3116         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3117         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3118         check_added_monitors!(nodes[2], 1);
3119
3120         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3121         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3122         check_added_monitors!(nodes[2], 1);
3123         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3124         assert!(updates.update_add_htlcs.is_empty());
3125         assert!(updates.update_fulfill_htlcs.is_empty());
3126         assert!(updates.update_fail_malformed_htlcs.is_empty());
3127         assert_eq!(updates.update_fail_htlcs.len(), 1);
3128         assert!(updates.update_fee.is_none());
3129         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3130         // At this point first_payment_hash has dropped out of the latest two commitment
3131         // transactions that nodes[1] is tracking...
3132         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3133         check_added_monitors!(nodes[1], 1);
3134         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3135         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3136         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3137         check_added_monitors!(nodes[2], 1);
3138
3139         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3140         // on nodes[2]'s RAA.
3141         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3142         nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3143         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3144         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3145         check_added_monitors!(nodes[1], 0);
3146
3147         if deliver_bs_raa {
3148                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3149                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3150                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3151                 check_added_monitors!(nodes[1], 1);
3152                 let events = nodes[1].node.get_and_clear_pending_events();
3153                 assert_eq!(events.len(), 2);
3154                 match events[0] {
3155                         Event::PendingHTLCsForwardable { .. } => { },
3156                         _ => panic!("Unexpected event"),
3157                 };
3158                 match events[1] {
3159                         Event::HTLCHandlingFailed { .. } => { },
3160                         _ => panic!("Unexpected event"),
3161                 }
3162                 // Deliberately don't process the pending fail-back so they all fail back at once after
3163                 // block connection just like the !deliver_bs_raa case
3164         }
3165
3166         let mut failed_htlcs = HashSet::new();
3167         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3168
3169         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3170         check_added_monitors!(nodes[1], 1);
3171         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3172
3173         let events = nodes[1].node.get_and_clear_pending_events();
3174         assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3175         match events[0] {
3176                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3177                 _ => panic!("Unexepected event"),
3178         }
3179         match events[1] {
3180                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3181                         assert_eq!(*payment_hash, fourth_payment_hash);
3182                 },
3183                 _ => panic!("Unexpected event"),
3184         }
3185         match events[2] {
3186                 Event::PaymentFailed { ref payment_hash, .. } => {
3187                         assert_eq!(*payment_hash, fourth_payment_hash);
3188                 },
3189                 _ => panic!("Unexpected event"),
3190         }
3191
3192         nodes[1].node.process_pending_htlc_forwards();
3193         check_added_monitors!(nodes[1], 1);
3194
3195         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3196         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3197
3198         if deliver_bs_raa {
3199                 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3200                 match nodes_2_event {
3201                         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, .. } } => {
3202                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3203                                 assert_eq!(update_add_htlcs.len(), 1);
3204                                 assert!(update_fulfill_htlcs.is_empty());
3205                                 assert!(update_fail_htlcs.is_empty());
3206                                 assert!(update_fail_malformed_htlcs.is_empty());
3207                         },
3208                         _ => panic!("Unexpected event"),
3209                 }
3210         }
3211
3212         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3213         match nodes_2_event {
3214                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3215                         assert_eq!(channel_id, chan_2.2);
3216                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3217                 },
3218                 _ => panic!("Unexpected event"),
3219         }
3220
3221         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3222         match nodes_0_event {
3223                 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, .. } } => {
3224                         assert!(update_add_htlcs.is_empty());
3225                         assert_eq!(update_fail_htlcs.len(), 3);
3226                         assert!(update_fulfill_htlcs.is_empty());
3227                         assert!(update_fail_malformed_htlcs.is_empty());
3228                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3229
3230                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3231                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3232                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3233
3234                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3235
3236                         let events = nodes[0].node.get_and_clear_pending_events();
3237                         assert_eq!(events.len(), 6);
3238                         match events[0] {
3239                                 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3240                                         assert!(failed_htlcs.insert(payment_hash.0));
3241                                         // If we delivered B's RAA we got an unknown preimage error, not something
3242                                         // that we should update our routing table for.
3243                                         if !deliver_bs_raa {
3244                                                 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3245                                         }
3246                                 },
3247                                 _ => panic!("Unexpected event"),
3248                         }
3249                         match events[1] {
3250                                 Event::PaymentFailed { ref payment_hash, .. } => {
3251                                         assert_eq!(*payment_hash, first_payment_hash);
3252                                 },
3253                                 _ => panic!("Unexpected event"),
3254                         }
3255                         match events[2] {
3256                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3257                                         assert!(failed_htlcs.insert(payment_hash.0));
3258                                 },
3259                                 _ => panic!("Unexpected event"),
3260                         }
3261                         match events[3] {
3262                                 Event::PaymentFailed { ref payment_hash, .. } => {
3263                                         assert_eq!(*payment_hash, second_payment_hash);
3264                                 },
3265                                 _ => panic!("Unexpected event"),
3266                         }
3267                         match events[4] {
3268                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3269                                         assert!(failed_htlcs.insert(payment_hash.0));
3270                                 },
3271                                 _ => panic!("Unexpected event"),
3272                         }
3273                         match events[5] {
3274                                 Event::PaymentFailed { ref payment_hash, .. } => {
3275                                         assert_eq!(*payment_hash, third_payment_hash);
3276                                 },
3277                                 _ => panic!("Unexpected event"),
3278                         }
3279                 },
3280                 _ => panic!("Unexpected event"),
3281         }
3282
3283         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3284         match events[0] {
3285                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3286                 _ => panic!("Unexpected event"),
3287         }
3288
3289         assert!(failed_htlcs.contains(&first_payment_hash.0));
3290         assert!(failed_htlcs.contains(&second_payment_hash.0));
3291         assert!(failed_htlcs.contains(&third_payment_hash.0));
3292 }
3293
3294 #[test]
3295 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3296         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3297         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3298         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3299         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3300 }
3301
3302 #[test]
3303 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3304         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3305         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3306         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3307         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3308 }
3309
3310 #[test]
3311 fn fail_backward_pending_htlc_upon_channel_failure() {
3312         let chanmon_cfgs = create_chanmon_cfgs(2);
3313         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3314         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3315         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3316         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3317
3318         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3319         {
3320                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3321                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
3322                 check_added_monitors!(nodes[0], 1);
3323
3324                 let payment_event = {
3325                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3326                         assert_eq!(events.len(), 1);
3327                         SendEvent::from_event(events.remove(0))
3328                 };
3329                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3330                 assert_eq!(payment_event.msgs.len(), 1);
3331         }
3332
3333         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3334         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3335         {
3336                 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3337                 check_added_monitors!(nodes[0], 0);
3338
3339                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3340         }
3341
3342         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3343         {
3344                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3345
3346                 let secp_ctx = Secp256k1::new();
3347                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3348                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3349                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3350                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3351                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3352
3353                 // Send a 0-msat update_add_htlc to fail the channel.
3354                 let update_add_htlc = msgs::UpdateAddHTLC {
3355                         channel_id: chan.2,
3356                         htlc_id: 0,
3357                         amount_msat: 0,
3358                         payment_hash,
3359                         cltv_expiry,
3360                         onion_routing_packet,
3361                 };
3362                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3363         }
3364         let events = nodes[0].node.get_and_clear_pending_events();
3365         assert_eq!(events.len(), 3);
3366         // Check that Alice fails backward the pending HTLC from the second payment.
3367         match events[0] {
3368                 Event::PaymentPathFailed { payment_hash, .. } => {
3369                         assert_eq!(payment_hash, failed_payment_hash);
3370                 },
3371                 _ => panic!("Unexpected event"),
3372         }
3373         match events[1] {
3374                 Event::PaymentFailed { payment_hash, .. } => {
3375                         assert_eq!(payment_hash, failed_payment_hash);
3376                 },
3377                 _ => panic!("Unexpected event"),
3378         }
3379         match events[2] {
3380                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3381                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3382                 },
3383                 _ => panic!("Unexpected event {:?}", events[1]),
3384         }
3385         check_closed_broadcast!(nodes[0], true);
3386         check_added_monitors!(nodes[0], 1);
3387 }
3388
3389 #[test]
3390 fn test_htlc_ignore_latest_remote_commitment() {
3391         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3392         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3393         let chanmon_cfgs = create_chanmon_cfgs(2);
3394         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3395         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3396         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3397         if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3398                 // We rely on the ability to connect a block redundantly, which isn't allowed via
3399                 // `chain::Listen`, so we never run the test if we randomly get assigned that
3400                 // connect_style.
3401                 return;
3402         }
3403         create_announced_chan_between_nodes(&nodes, 0, 1);
3404
3405         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3406         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3407         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3408         check_closed_broadcast!(nodes[0], true);
3409         check_added_monitors!(nodes[0], 1);
3410         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3411
3412         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3413         assert_eq!(node_txn.len(), 3);
3414         assert_eq!(node_txn[0], node_txn[1]);
3415
3416         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
3417         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3418         check_closed_broadcast!(nodes[1], true);
3419         check_added_monitors!(nodes[1], 1);
3420         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3421
3422         // Duplicate the connect_block call since this may happen due to other listeners
3423         // registering new transactions
3424         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3425 }
3426
3427 #[test]
3428 fn test_force_close_fail_back() {
3429         // Check which HTLCs are failed-backwards on channel force-closure
3430         let chanmon_cfgs = create_chanmon_cfgs(3);
3431         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3432         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3433         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3434         create_announced_chan_between_nodes(&nodes, 0, 1);
3435         create_announced_chan_between_nodes(&nodes, 1, 2);
3436
3437         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3438
3439         let mut payment_event = {
3440                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3441                 check_added_monitors!(nodes[0], 1);
3442
3443                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3444                 assert_eq!(events.len(), 1);
3445                 SendEvent::from_event(events.remove(0))
3446         };
3447
3448         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3449         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3450
3451         expect_pending_htlcs_forwardable!(nodes[1]);
3452
3453         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3454         assert_eq!(events_2.len(), 1);
3455         payment_event = SendEvent::from_event(events_2.remove(0));
3456         assert_eq!(payment_event.msgs.len(), 1);
3457
3458         check_added_monitors!(nodes[1], 1);
3459         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3460         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3461         check_added_monitors!(nodes[2], 1);
3462         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3463
3464         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3465         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3466         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3467
3468         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3469         check_closed_broadcast!(nodes[2], true);
3470         check_added_monitors!(nodes[2], 1);
3471         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3472         let tx = {
3473                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3474                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3475                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3476                 // back to nodes[1] upon timeout otherwise.
3477                 assert_eq!(node_txn.len(), 1);
3478                 node_txn.remove(0)
3479         };
3480
3481         mine_transaction(&nodes[1], &tx);
3482
3483         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3484         check_closed_broadcast!(nodes[1], true);
3485         check_added_monitors!(nodes[1], 1);
3486         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3487
3488         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3489         {
3490                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3491                         .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);
3492         }
3493         mine_transaction(&nodes[2], &tx);
3494         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3495         assert_eq!(node_txn.len(), 1);
3496         assert_eq!(node_txn[0].input.len(), 1);
3497         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3498         assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3499         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3500
3501         check_spends!(node_txn[0], tx);
3502 }
3503
3504 #[test]
3505 fn test_dup_events_on_peer_disconnect() {
3506         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3507         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3508         // as we used to generate the event immediately upon receipt of the payment preimage in the
3509         // update_fulfill_htlc message.
3510
3511         let chanmon_cfgs = create_chanmon_cfgs(2);
3512         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3513         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3514         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3515         create_announced_chan_between_nodes(&nodes, 0, 1);
3516
3517         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3518
3519         nodes[1].node.claim_funds(payment_preimage);
3520         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3521         check_added_monitors!(nodes[1], 1);
3522         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3523         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3524         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3525
3526         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3527         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3528
3529         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3530         expect_payment_path_successful!(nodes[0]);
3531 }
3532
3533 #[test]
3534 fn test_peer_disconnected_before_funding_broadcasted() {
3535         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3536         // before the funding transaction has been broadcasted.
3537         let chanmon_cfgs = create_chanmon_cfgs(2);
3538         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3539         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3540         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3541
3542         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3543         // broadcasted, even though it's created by `nodes[0]`.
3544         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();
3545         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3546         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3547         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3548         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3549
3550         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3551         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3552
3553         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3554
3555         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3556         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3557
3558         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3559         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3560         // broadcasted.
3561         {
3562                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3563         }
3564
3565         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3566         // disconnected before the funding transaction was broadcasted.
3567         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3568         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3569
3570         check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3571         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3572 }
3573
3574 #[test]
3575 fn test_simple_peer_disconnect() {
3576         // Test that we can reconnect when there are no lost messages
3577         let chanmon_cfgs = create_chanmon_cfgs(3);
3578         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3579         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3580         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3581         create_announced_chan_between_nodes(&nodes, 0, 1);
3582         create_announced_chan_between_nodes(&nodes, 1, 2);
3583
3584         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3585         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3586         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3587
3588         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3589         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3590         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3591         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3592
3593         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3594         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3595         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3596
3597         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3598         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3599         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3600         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3601
3602         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3603         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3604
3605         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3606         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3607
3608         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3609         {
3610                 let events = nodes[0].node.get_and_clear_pending_events();
3611                 assert_eq!(events.len(), 4);
3612                 match events[0] {
3613                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3614                                 assert_eq!(payment_preimage, payment_preimage_3);
3615                                 assert_eq!(payment_hash, payment_hash_3);
3616                         },
3617                         _ => panic!("Unexpected event"),
3618                 }
3619                 match events[1] {
3620                         Event::PaymentPathSuccessful { .. } => {},
3621                         _ => panic!("Unexpected event"),
3622                 }
3623                 match events[2] {
3624                         Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3625                                 assert_eq!(payment_hash, payment_hash_5);
3626                                 assert!(payment_failed_permanently);
3627                         },
3628                         _ => panic!("Unexpected event"),
3629                 }
3630                 match events[3] {
3631                         Event::PaymentFailed { payment_hash, .. } => {
3632                                 assert_eq!(payment_hash, payment_hash_5);
3633                         },
3634                         _ => panic!("Unexpected event"),
3635                 }
3636         }
3637
3638         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3639         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3640 }
3641
3642 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3643         // Test that we can reconnect when in-flight HTLC updates get dropped
3644         let chanmon_cfgs = create_chanmon_cfgs(2);
3645         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3646         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3647         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3648
3649         let mut as_channel_ready = None;
3650         let channel_id = if messages_delivered == 0 {
3651                 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3652                 as_channel_ready = Some(channel_ready);
3653                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3654                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3655                 // it before the channel_reestablish message.
3656                 chan_id
3657         } else {
3658                 create_announced_chan_between_nodes(&nodes, 0, 1).2
3659         };
3660
3661         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3662
3663         let payment_event = {
3664                 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3665                 check_added_monitors!(nodes[0], 1);
3666
3667                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3668                 assert_eq!(events.len(), 1);
3669                 SendEvent::from_event(events.remove(0))
3670         };
3671         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3672
3673         if messages_delivered < 2 {
3674                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3675         } else {
3676                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3677                 if messages_delivered >= 3 {
3678                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3679                         check_added_monitors!(nodes[1], 1);
3680                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3681
3682                         if messages_delivered >= 4 {
3683                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3684                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3685                                 check_added_monitors!(nodes[0], 1);
3686
3687                                 if messages_delivered >= 5 {
3688                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3689                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3690                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3691                                         check_added_monitors!(nodes[0], 1);
3692
3693                                         if messages_delivered >= 6 {
3694                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3695                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3696                                                 check_added_monitors!(nodes[1], 1);
3697                                         }
3698                                 }
3699                         }
3700                 }
3701         }
3702
3703         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3704         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3705         if messages_delivered < 3 {
3706                 if simulate_broken_lnd {
3707                         // lnd has a long-standing bug where they send a channel_ready prior to a
3708                         // channel_reestablish if you reconnect prior to channel_ready time.
3709                         //
3710                         // Here we simulate that behavior, delivering a channel_ready immediately on
3711                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3712                         // in `reconnect_nodes` but we currently don't fail based on that.
3713                         //
3714                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3715                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3716                 }
3717                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3718                 // received on either side, both sides will need to resend them.
3719                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3720         } else if messages_delivered == 3 {
3721                 // nodes[0] still wants its RAA + commitment_signed
3722                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3723         } else if messages_delivered == 4 {
3724                 // nodes[0] still wants its commitment_signed
3725                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3726         } else if messages_delivered == 5 {
3727                 // nodes[1] still wants its final RAA
3728                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3729         } else if messages_delivered == 6 {
3730                 // Everything was delivered...
3731                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3732         }
3733
3734         let events_1 = nodes[1].node.get_and_clear_pending_events();
3735         if messages_delivered == 0 {
3736                 assert_eq!(events_1.len(), 2);
3737                 match events_1[0] {
3738                         Event::ChannelReady { .. } => { },
3739                         _ => panic!("Unexpected event"),
3740                 };
3741                 match events_1[1] {
3742                         Event::PendingHTLCsForwardable { .. } => { },
3743                         _ => panic!("Unexpected event"),
3744                 };
3745         } else {
3746                 assert_eq!(events_1.len(), 1);
3747                 match events_1[0] {
3748                         Event::PendingHTLCsForwardable { .. } => { },
3749                         _ => panic!("Unexpected event"),
3750                 };
3751         }
3752
3753         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3754         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3755         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3756
3757         nodes[1].node.process_pending_htlc_forwards();
3758
3759         let events_2 = nodes[1].node.get_and_clear_pending_events();
3760         assert_eq!(events_2.len(), 1);
3761         match events_2[0] {
3762                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
3763                         assert_eq!(payment_hash_1, *payment_hash);
3764                         assert_eq!(amount_msat, 1_000_000);
3765                         assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3766                         assert_eq!(via_channel_id, Some(channel_id));
3767                         match &purpose {
3768                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3769                                         assert!(payment_preimage.is_none());
3770                                         assert_eq!(payment_secret_1, *payment_secret);
3771                                 },
3772                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3773                         }
3774                 },
3775                 _ => panic!("Unexpected event"),
3776         }
3777
3778         nodes[1].node.claim_funds(payment_preimage_1);
3779         check_added_monitors!(nodes[1], 1);
3780         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3781
3782         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3783         assert_eq!(events_3.len(), 1);
3784         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3785                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3786                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3787                         assert!(updates.update_add_htlcs.is_empty());
3788                         assert!(updates.update_fail_htlcs.is_empty());
3789                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3790                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3791                         assert!(updates.update_fee.is_none());
3792                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3793                 },
3794                 _ => panic!("Unexpected event"),
3795         };
3796
3797         if messages_delivered >= 1 {
3798                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3799
3800                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3801                 assert_eq!(events_4.len(), 1);
3802                 match events_4[0] {
3803                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3804                                 assert_eq!(payment_preimage_1, *payment_preimage);
3805                                 assert_eq!(payment_hash_1, *payment_hash);
3806                         },
3807                         _ => panic!("Unexpected event"),
3808                 }
3809
3810                 if messages_delivered >= 2 {
3811                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3812                         check_added_monitors!(nodes[0], 1);
3813                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3814
3815                         if messages_delivered >= 3 {
3816                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3817                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3818                                 check_added_monitors!(nodes[1], 1);
3819
3820                                 if messages_delivered >= 4 {
3821                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3822                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3823                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3824                                         check_added_monitors!(nodes[1], 1);
3825
3826                                         if messages_delivered >= 5 {
3827                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3828                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3829                                                 check_added_monitors!(nodes[0], 1);
3830                                         }
3831                                 }
3832                         }
3833                 }
3834         }
3835
3836         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3837         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3838         if messages_delivered < 2 {
3839                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3840                 if messages_delivered < 1 {
3841                         expect_payment_sent!(nodes[0], payment_preimage_1);
3842                 } else {
3843                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3844                 }
3845         } else if messages_delivered == 2 {
3846                 // nodes[0] still wants its RAA + commitment_signed
3847                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3848         } else if messages_delivered == 3 {
3849                 // nodes[0] still wants its commitment_signed
3850                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3851         } else if messages_delivered == 4 {
3852                 // nodes[1] still wants its final RAA
3853                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3854         } else if messages_delivered == 5 {
3855                 // Everything was delivered...
3856                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3857         }
3858
3859         if messages_delivered == 1 || messages_delivered == 2 {
3860                 expect_payment_path_successful!(nodes[0]);
3861         }
3862         if messages_delivered <= 5 {
3863                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3864                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3865         }
3866         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3867
3868         if messages_delivered > 2 {
3869                 expect_payment_path_successful!(nodes[0]);
3870         }
3871
3872         // Channel should still work fine...
3873         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3874         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3875         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3876 }
3877
3878 #[test]
3879 fn test_drop_messages_peer_disconnect_a() {
3880         do_test_drop_messages_peer_disconnect(0, true);
3881         do_test_drop_messages_peer_disconnect(0, false);
3882         do_test_drop_messages_peer_disconnect(1, false);
3883         do_test_drop_messages_peer_disconnect(2, false);
3884 }
3885
3886 #[test]
3887 fn test_drop_messages_peer_disconnect_b() {
3888         do_test_drop_messages_peer_disconnect(3, false);
3889         do_test_drop_messages_peer_disconnect(4, false);
3890         do_test_drop_messages_peer_disconnect(5, false);
3891         do_test_drop_messages_peer_disconnect(6, false);
3892 }
3893
3894 #[test]
3895 fn test_channel_ready_without_best_block_updated() {
3896         // Previously, if we were offline when a funding transaction was locked in, and then we came
3897         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3898         // generate a channel_ready until a later best_block_updated. This tests that we generate the
3899         // channel_ready immediately instead.
3900         let chanmon_cfgs = create_chanmon_cfgs(2);
3901         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3902         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3903         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3904         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3905
3906         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
3907
3908         let conf_height = nodes[0].best_block_info().1 + 1;
3909         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3910         let block_txn = [funding_tx];
3911         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3912         let conf_block_header = nodes[0].get_block_header(conf_height);
3913         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3914
3915         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
3916         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
3917         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3918 }
3919
3920 #[test]
3921 fn test_drop_messages_peer_disconnect_dual_htlc() {
3922         // Test that we can handle reconnecting when both sides of a channel have pending
3923         // commitment_updates when we disconnect.
3924         let chanmon_cfgs = create_chanmon_cfgs(2);
3925         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3926         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3927         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3928         create_announced_chan_between_nodes(&nodes, 0, 1);
3929
3930         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3931
3932         // Now try to send a second payment which will fail to send
3933         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3934         nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
3935         check_added_monitors!(nodes[0], 1);
3936
3937         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3938         assert_eq!(events_1.len(), 1);
3939         match events_1[0] {
3940                 MessageSendEvent::UpdateHTLCs { .. } => {},
3941                 _ => panic!("Unexpected event"),
3942         }
3943
3944         nodes[1].node.claim_funds(payment_preimage_1);
3945         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3946         check_added_monitors!(nodes[1], 1);
3947
3948         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3949         assert_eq!(events_2.len(), 1);
3950         match events_2[0] {
3951                 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 } } => {
3952                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3953                         assert!(update_add_htlcs.is_empty());
3954                         assert_eq!(update_fulfill_htlcs.len(), 1);
3955                         assert!(update_fail_htlcs.is_empty());
3956                         assert!(update_fail_malformed_htlcs.is_empty());
3957                         assert!(update_fee.is_none());
3958
3959                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3960                         let events_3 = nodes[0].node.get_and_clear_pending_events();
3961                         assert_eq!(events_3.len(), 1);
3962                         match events_3[0] {
3963                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3964                                         assert_eq!(*payment_preimage, payment_preimage_1);
3965                                         assert_eq!(*payment_hash, payment_hash_1);
3966                                 },
3967                                 _ => panic!("Unexpected event"),
3968                         }
3969
3970                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3971                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3972                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3973                         check_added_monitors!(nodes[0], 1);
3974                 },
3975                 _ => panic!("Unexpected event"),
3976         }
3977
3978         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3979         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3980
3981         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }, true).unwrap();
3982         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3983         assert_eq!(reestablish_1.len(), 1);
3984         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }, false).unwrap();
3985         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3986         assert_eq!(reestablish_2.len(), 1);
3987
3988         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3989         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3990         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3991         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3992
3993         assert!(as_resp.0.is_none());
3994         assert!(bs_resp.0.is_none());
3995
3996         assert!(bs_resp.1.is_none());
3997         assert!(bs_resp.2.is_none());
3998
3999         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4000
4001         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4002         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4003         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4004         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4005         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4006         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4007         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4008         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4009         // No commitment_signed so get_event_msg's assert(len == 1) passes
4010         check_added_monitors!(nodes[1], 1);
4011
4012         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4013         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4014         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4015         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4016         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4017         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4018         assert!(bs_second_commitment_signed.update_fee.is_none());
4019         check_added_monitors!(nodes[1], 1);
4020
4021         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4022         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4023         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4024         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4025         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4026         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4027         assert!(as_commitment_signed.update_fee.is_none());
4028         check_added_monitors!(nodes[0], 1);
4029
4030         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4031         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4032         // No commitment_signed so get_event_msg's assert(len == 1) passes
4033         check_added_monitors!(nodes[0], 1);
4034
4035         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4036         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4037         // No commitment_signed so get_event_msg's assert(len == 1) passes
4038         check_added_monitors!(nodes[1], 1);
4039
4040         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4041         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4042         check_added_monitors!(nodes[1], 1);
4043
4044         expect_pending_htlcs_forwardable!(nodes[1]);
4045
4046         let events_5 = nodes[1].node.get_and_clear_pending_events();
4047         assert_eq!(events_5.len(), 1);
4048         match events_5[0] {
4049                 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4050                         assert_eq!(payment_hash_2, *payment_hash);
4051                         match &purpose {
4052                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4053                                         assert!(payment_preimage.is_none());
4054                                         assert_eq!(payment_secret_2, *payment_secret);
4055                                 },
4056                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4057                         }
4058                 },
4059                 _ => panic!("Unexpected event"),
4060         }
4061
4062         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4063         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4064         check_added_monitors!(nodes[0], 1);
4065
4066         expect_payment_path_successful!(nodes[0]);
4067         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4068 }
4069
4070 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4071         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4072         // to avoid our counterparty failing the channel.
4073         let chanmon_cfgs = create_chanmon_cfgs(2);
4074         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4075         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4076         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4077
4078         create_announced_chan_between_nodes(&nodes, 0, 1);
4079
4080         let our_payment_hash = if send_partial_mpp {
4081                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4082                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4083                 // indicates there are more HTLCs coming.
4084                 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.
4085                 let payment_id = PaymentId([42; 32]);
4086                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(payment_secret), payment_id, &route).unwrap();
4087                 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[0]).unwrap();
4088                 check_added_monitors!(nodes[0], 1);
4089                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4090                 assert_eq!(events.len(), 1);
4091                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4092                 // hop should *not* yet generate any PaymentClaimable event(s).
4093                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4094                 our_payment_hash
4095         } else {
4096                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4097         };
4098
4099         let mut block = Block {
4100                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
4101                 txdata: vec![],
4102         };
4103         connect_block(&nodes[0], &block);
4104         connect_block(&nodes[1], &block);
4105         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4106         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4107                 block.header.prev_blockhash = block.block_hash();
4108                 connect_block(&nodes[0], &block);
4109                 connect_block(&nodes[1], &block);
4110         }
4111
4112         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4113
4114         check_added_monitors!(nodes[1], 1);
4115         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4116         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4117         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4118         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4119         assert!(htlc_timeout_updates.update_fee.is_none());
4120
4121         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4122         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4123         // 100_000 msat as u64, followed by the height at which we failed back above
4124         let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4125         expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4126         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4127 }
4128
4129 #[test]
4130 fn test_htlc_timeout() {
4131         do_test_htlc_timeout(true);
4132         do_test_htlc_timeout(false);
4133 }
4134
4135 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4136         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4137         let chanmon_cfgs = create_chanmon_cfgs(3);
4138         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4139         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4140         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4141         create_announced_chan_between_nodes(&nodes, 0, 1);
4142         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4143
4144         // Make sure all nodes are at the same starting height
4145         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4146         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4147         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4148
4149         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4150         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4151         {
4152                 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4153         }
4154         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4155         check_added_monitors!(nodes[1], 1);
4156
4157         // Now attempt to route a second payment, which should be placed in the holding cell
4158         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4159         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4160         sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4161         if forwarded_htlc {
4162                 check_added_monitors!(nodes[0], 1);
4163                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4164                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4165                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4166                 expect_pending_htlcs_forwardable!(nodes[1]);
4167         }
4168         check_added_monitors!(nodes[1], 0);
4169
4170         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4171         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4172         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4173         connect_blocks(&nodes[1], 1);
4174
4175         if forwarded_htlc {
4176                 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 }]);
4177                 check_added_monitors!(nodes[1], 1);
4178                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4179                 assert_eq!(fail_commit.len(), 1);
4180                 match fail_commit[0] {
4181                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4182                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4183                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4184                         },
4185                         _ => unreachable!(),
4186                 }
4187                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4188         } else {
4189                 expect_payment_failed!(nodes[1], second_payment_hash, false);
4190         }
4191 }
4192
4193 #[test]
4194 fn test_holding_cell_htlc_add_timeouts() {
4195         do_test_holding_cell_htlc_add_timeouts(false);
4196         do_test_holding_cell_htlc_add_timeouts(true);
4197 }
4198
4199 macro_rules! check_spendable_outputs {
4200         ($node: expr, $keysinterface: expr) => {
4201                 {
4202                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4203                         let mut txn = Vec::new();
4204                         let mut all_outputs = Vec::new();
4205                         let secp_ctx = Secp256k1::new();
4206                         for event in events.drain(..) {
4207                                 match event {
4208                                         Event::SpendableOutputs { mut outputs } => {
4209                                                 for outp in outputs.drain(..) {
4210                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4211                                                         all_outputs.push(outp);
4212                                                 }
4213                                         },
4214                                         _ => panic!("Unexpected event"),
4215                                 };
4216                         }
4217                         if all_outputs.len() > 1 {
4218                                 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) {
4219                                         txn.push(tx);
4220                                 }
4221                         }
4222                         txn
4223                 }
4224         }
4225 }
4226
4227 #[test]
4228 fn test_claim_sizeable_push_msat() {
4229         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4230         let chanmon_cfgs = create_chanmon_cfgs(2);
4231         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4232         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4233         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4234
4235         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4236         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4237         check_closed_broadcast!(nodes[1], true);
4238         check_added_monitors!(nodes[1], 1);
4239         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4240         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4241         assert_eq!(node_txn.len(), 1);
4242         check_spends!(node_txn[0], chan.3);
4243         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
4244
4245         mine_transaction(&nodes[1], &node_txn[0]);
4246         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4247
4248         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4249         assert_eq!(spend_txn.len(), 1);
4250         assert_eq!(spend_txn[0].input.len(), 1);
4251         check_spends!(spend_txn[0], node_txn[0]);
4252         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4253 }
4254
4255 #[test]
4256 fn test_claim_on_remote_sizeable_push_msat() {
4257         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4258         // to_remote output is encumbered by a P2WPKH
4259         let chanmon_cfgs = create_chanmon_cfgs(2);
4260         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4261         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4262         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4263
4264         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4265         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4266         check_closed_broadcast!(nodes[0], true);
4267         check_added_monitors!(nodes[0], 1);
4268         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4269
4270         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4271         assert_eq!(node_txn.len(), 1);
4272         check_spends!(node_txn[0], chan.3);
4273         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
4274
4275         mine_transaction(&nodes[1], &node_txn[0]);
4276         check_closed_broadcast!(nodes[1], true);
4277         check_added_monitors!(nodes[1], 1);
4278         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4279         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4280
4281         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4282         assert_eq!(spend_txn.len(), 1);
4283         check_spends!(spend_txn[0], node_txn[0]);
4284 }
4285
4286 #[test]
4287 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4288         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4289         // to_remote output is encumbered by a P2WPKH
4290
4291         let chanmon_cfgs = create_chanmon_cfgs(2);
4292         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4293         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4294         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4295
4296         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4297         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4298         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4299         assert_eq!(revoked_local_txn[0].input.len(), 1);
4300         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4301
4302         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4303         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4304         check_closed_broadcast!(nodes[1], true);
4305         check_added_monitors!(nodes[1], 1);
4306         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4307
4308         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4309         mine_transaction(&nodes[1], &node_txn[0]);
4310         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4311
4312         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4313         assert_eq!(spend_txn.len(), 3);
4314         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4315         check_spends!(spend_txn[1], node_txn[0]);
4316         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4317 }
4318
4319 #[test]
4320 fn test_static_spendable_outputs_preimage_tx() {
4321         let chanmon_cfgs = create_chanmon_cfgs(2);
4322         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4323         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4324         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4325
4326         // Create some initial channels
4327         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4328
4329         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4330
4331         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4332         assert_eq!(commitment_tx[0].input.len(), 1);
4333         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4334
4335         // Settle A's commitment tx on B's chain
4336         nodes[1].node.claim_funds(payment_preimage);
4337         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4338         check_added_monitors!(nodes[1], 1);
4339         mine_transaction(&nodes[1], &commitment_tx[0]);
4340         check_added_monitors!(nodes[1], 1);
4341         let events = nodes[1].node.get_and_clear_pending_msg_events();
4342         match events[0] {
4343                 MessageSendEvent::UpdateHTLCs { .. } => {},
4344                 _ => panic!("Unexpected event"),
4345         }
4346         match events[1] {
4347                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4348                 _ => panic!("Unexepected event"),
4349         }
4350
4351         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4352         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4353         assert_eq!(node_txn.len(), 1);
4354         check_spends!(node_txn[0], commitment_tx[0]);
4355         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4356
4357         mine_transaction(&nodes[1], &node_txn[0]);
4358         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4359         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4360
4361         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4362         assert_eq!(spend_txn.len(), 1);
4363         check_spends!(spend_txn[0], node_txn[0]);
4364 }
4365
4366 #[test]
4367 fn test_static_spendable_outputs_timeout_tx() {
4368         let chanmon_cfgs = create_chanmon_cfgs(2);
4369         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4370         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4371         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4372
4373         // Create some initial channels
4374         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4375
4376         // Rebalance the network a bit by relaying one payment through all the channels ...
4377         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4378
4379         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4380
4381         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4382         assert_eq!(commitment_tx[0].input.len(), 1);
4383         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4384
4385         // Settle A's commitment tx on B' chain
4386         mine_transaction(&nodes[1], &commitment_tx[0]);
4387         check_added_monitors!(nodes[1], 1);
4388         let events = nodes[1].node.get_and_clear_pending_msg_events();
4389         match events[0] {
4390                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4391                 _ => panic!("Unexpected event"),
4392         }
4393         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4394
4395         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4396         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4397         assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4398         check_spends!(node_txn[0],  commitment_tx[0].clone());
4399         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4400
4401         mine_transaction(&nodes[1], &node_txn[0]);
4402         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4403         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4404         expect_payment_failed!(nodes[1], our_payment_hash, false);
4405
4406         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4407         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4408         check_spends!(spend_txn[0], commitment_tx[0]);
4409         check_spends!(spend_txn[1], node_txn[0]);
4410         check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4411 }
4412
4413 #[test]
4414 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4415         let chanmon_cfgs = create_chanmon_cfgs(2);
4416         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4417         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4418         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4419
4420         // Create some initial channels
4421         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4422
4423         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4424         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4425         assert_eq!(revoked_local_txn[0].input.len(), 1);
4426         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4427
4428         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4429
4430         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4431         check_closed_broadcast!(nodes[1], true);
4432         check_added_monitors!(nodes[1], 1);
4433         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4434
4435         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4436         assert_eq!(node_txn.len(), 1);
4437         assert_eq!(node_txn[0].input.len(), 2);
4438         check_spends!(node_txn[0], revoked_local_txn[0]);
4439
4440         mine_transaction(&nodes[1], &node_txn[0]);
4441         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4442
4443         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4444         assert_eq!(spend_txn.len(), 1);
4445         check_spends!(spend_txn[0], node_txn[0]);
4446 }
4447
4448 #[test]
4449 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4450         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4451         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4452         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4453         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4454         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4455
4456         // Create some initial channels
4457         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4458
4459         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4460         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4461         assert_eq!(revoked_local_txn[0].input.len(), 1);
4462         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4463
4464         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4465
4466         // A will generate HTLC-Timeout from revoked commitment tx
4467         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4468         check_closed_broadcast!(nodes[0], true);
4469         check_added_monitors!(nodes[0], 1);
4470         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4471         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4472
4473         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4474         assert_eq!(revoked_htlc_txn.len(), 1);
4475         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4476         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4477         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4478         assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4479
4480         // B will generate justice tx from A's revoked commitment/HTLC tx
4481         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4482         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4483         check_closed_broadcast!(nodes[1], true);
4484         check_added_monitors!(nodes[1], 1);
4485         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4486
4487         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4488         assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4489         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4490         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4491         // transactions next...
4492         assert_eq!(node_txn[0].input.len(), 3);
4493         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4494
4495         assert_eq!(node_txn[1].input.len(), 2);
4496         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4497         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4498                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4499         } else {
4500                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4501                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4502         }
4503
4504         mine_transaction(&nodes[1], &node_txn[1]);
4505         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4506
4507         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4508         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4509         assert_eq!(spend_txn.len(), 1);
4510         assert_eq!(spend_txn[0].input.len(), 1);
4511         check_spends!(spend_txn[0], node_txn[1]);
4512 }
4513
4514 #[test]
4515 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4516         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4517         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4518         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4519         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4520         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4521
4522         // Create some initial channels
4523         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4524
4525         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4526         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4527         assert_eq!(revoked_local_txn[0].input.len(), 1);
4528         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4529
4530         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4531         assert_eq!(revoked_local_txn[0].output.len(), 2);
4532
4533         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4534
4535         // B will generate HTLC-Success from revoked commitment tx
4536         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4537         check_closed_broadcast!(nodes[1], true);
4538         check_added_monitors!(nodes[1], 1);
4539         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4540         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4541
4542         assert_eq!(revoked_htlc_txn.len(), 1);
4543         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4544         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4545         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4546
4547         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4548         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4549         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4550
4551         // A will generate justice tx from B's revoked commitment/HTLC tx
4552         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4553         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4554         check_closed_broadcast!(nodes[0], true);
4555         check_added_monitors!(nodes[0], 1);
4556         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4557
4558         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4559         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4560
4561         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4562         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4563         // transactions next...
4564         assert_eq!(node_txn[0].input.len(), 2);
4565         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4566         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4567                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4568         } else {
4569                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4570                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4571         }
4572
4573         assert_eq!(node_txn[1].input.len(), 1);
4574         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4575
4576         mine_transaction(&nodes[0], &node_txn[1]);
4577         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4578
4579         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4580         // didn't try to generate any new transactions.
4581
4582         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4583         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4584         assert_eq!(spend_txn.len(), 3);
4585         assert_eq!(spend_txn[0].input.len(), 1);
4586         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4587         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4588         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4589         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4590 }
4591
4592 #[test]
4593 fn test_onchain_to_onchain_claim() {
4594         // Test that in case of channel closure, we detect the state of output and claim HTLC
4595         // on downstream peer's remote commitment tx.
4596         // First, have C claim an HTLC against its own latest commitment transaction.
4597         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4598         // channel.
4599         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4600         // gets broadcast.
4601
4602         let chanmon_cfgs = create_chanmon_cfgs(3);
4603         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4604         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4605         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4606
4607         // Create some initial channels
4608         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4609         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4610
4611         // Ensure all nodes are at the same height
4612         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4613         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4614         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4615         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4616
4617         // Rebalance the network a bit by relaying one payment through all the channels ...
4618         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4619         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4620
4621         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4622         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4623         check_spends!(commitment_tx[0], chan_2.3);
4624         nodes[2].node.claim_funds(payment_preimage);
4625         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4626         check_added_monitors!(nodes[2], 1);
4627         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4628         assert!(updates.update_add_htlcs.is_empty());
4629         assert!(updates.update_fail_htlcs.is_empty());
4630         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4631         assert!(updates.update_fail_malformed_htlcs.is_empty());
4632
4633         mine_transaction(&nodes[2], &commitment_tx[0]);
4634         check_closed_broadcast!(nodes[2], true);
4635         check_added_monitors!(nodes[2], 1);
4636         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4637
4638         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4639         assert_eq!(c_txn.len(), 1);
4640         check_spends!(c_txn[0], commitment_tx[0]);
4641         assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4642         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4643         assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4644
4645         // 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
4646         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
4647         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone(), c_txn[0].clone()]});
4648         check_added_monitors!(nodes[1], 1);
4649         let events = nodes[1].node.get_and_clear_pending_events();
4650         assert_eq!(events.len(), 2);
4651         match events[0] {
4652                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4653                 _ => panic!("Unexpected event"),
4654         }
4655         match events[1] {
4656                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
4657                         assert_eq!(fee_earned_msat, Some(1000));
4658                         assert_eq!(prev_channel_id, Some(chan_1.2));
4659                         assert_eq!(claim_from_onchain_tx, true);
4660                         assert_eq!(next_channel_id, Some(chan_2.2));
4661                 },
4662                 _ => panic!("Unexpected event"),
4663         }
4664         check_added_monitors!(nodes[1], 1);
4665         let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4666         assert_eq!(msg_events.len(), 3);
4667         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4668         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4669
4670         match nodes_2_event {
4671                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4672                 _ => panic!("Unexpected event"),
4673         }
4674
4675         match nodes_0_event {
4676                 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, .. } } => {
4677                         assert!(update_add_htlcs.is_empty());
4678                         assert!(update_fail_htlcs.is_empty());
4679                         assert_eq!(update_fulfill_htlcs.len(), 1);
4680                         assert!(update_fail_malformed_htlcs.is_empty());
4681                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4682                 },
4683                 _ => panic!("Unexpected event"),
4684         };
4685
4686         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4687         match msg_events[0] {
4688                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4689                 _ => panic!("Unexpected event"),
4690         }
4691
4692         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4693         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4694         mine_transaction(&nodes[1], &commitment_tx[0]);
4695         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4696         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4697         // ChannelMonitor: HTLC-Success tx
4698         assert_eq!(b_txn.len(), 1);
4699         check_spends!(b_txn[0], commitment_tx[0]);
4700         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4701         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4702         assert_eq!(b_txn[0].lock_time.0, 0); // Success tx
4703
4704         check_closed_broadcast!(nodes[1], true);
4705         check_added_monitors!(nodes[1], 1);
4706 }
4707
4708 #[test]
4709 fn test_duplicate_payment_hash_one_failure_one_success() {
4710         // Topology : A --> B --> C --> D
4711         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4712         // Note that because C will refuse to generate two payment secrets for the same payment hash,
4713         // we forward one of the payments onwards to D.
4714         let chanmon_cfgs = create_chanmon_cfgs(4);
4715         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4716         // When this test was written, the default base fee floated based on the HTLC count.
4717         // It is now fixed, so we simply set the fee to the expected value here.
4718         let mut config = test_default_channel_config();
4719         config.channel_config.forwarding_fee_base_msat = 196;
4720         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4721                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4722         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4723
4724         create_announced_chan_between_nodes(&nodes, 0, 1);
4725         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4726         create_announced_chan_between_nodes(&nodes, 2, 3);
4727
4728         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4729         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4730         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4731         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4732         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4733
4734         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4735
4736         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4737         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4738         // script push size limit so that the below script length checks match
4739         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4740         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4741                 .with_features(nodes[3].node.invoice_features());
4742         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000, TEST_FINAL_CLTV - 40);
4743         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4744
4745         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4746         assert_eq!(commitment_txn[0].input.len(), 1);
4747         check_spends!(commitment_txn[0], chan_2.3);
4748
4749         mine_transaction(&nodes[1], &commitment_txn[0]);
4750         check_closed_broadcast!(nodes[1], true);
4751         check_added_monitors!(nodes[1], 1);
4752         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4753         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
4754
4755         let htlc_timeout_tx;
4756         { // Extract one of the two HTLC-Timeout transaction
4757                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4758                 // ChannelMonitor: timeout tx * 2-or-3
4759                 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4760
4761                 check_spends!(node_txn[0], commitment_txn[0]);
4762                 assert_eq!(node_txn[0].input.len(), 1);
4763                 assert_eq!(node_txn[0].output.len(), 1);
4764
4765                 if node_txn.len() > 2 {
4766                         check_spends!(node_txn[1], commitment_txn[0]);
4767                         assert_eq!(node_txn[1].input.len(), 1);
4768                         assert_eq!(node_txn[1].output.len(), 1);
4769                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4770
4771                         check_spends!(node_txn[2], commitment_txn[0]);
4772                         assert_eq!(node_txn[2].input.len(), 1);
4773                         assert_eq!(node_txn[2].output.len(), 1);
4774                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4775                 } else {
4776                         check_spends!(node_txn[1], commitment_txn[0]);
4777                         assert_eq!(node_txn[1].input.len(), 1);
4778                         assert_eq!(node_txn[1].output.len(), 1);
4779                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4780                 }
4781
4782                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4783                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4784                 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
4785                 // (with value 900 sats) will be claimed in the below `claim_funds` call.
4786                 if node_txn.len() > 2 {
4787                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4788                         htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
4789                 } else {
4790                         htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
4791                 }
4792         }
4793
4794         nodes[2].node.claim_funds(our_payment_preimage);
4795         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4796
4797         mine_transaction(&nodes[2], &commitment_txn[0]);
4798         check_added_monitors!(nodes[2], 2);
4799         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4800         let events = nodes[2].node.get_and_clear_pending_msg_events();
4801         match events[0] {
4802                 MessageSendEvent::UpdateHTLCs { .. } => {},
4803                 _ => panic!("Unexpected event"),
4804         }
4805         match events[1] {
4806                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4807                 _ => panic!("Unexepected event"),
4808         }
4809         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4810         assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4811         check_spends!(htlc_success_txn[0], commitment_txn[0]);
4812         check_spends!(htlc_success_txn[1], commitment_txn[0]);
4813         assert_eq!(htlc_success_txn[0].input.len(), 1);
4814         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4815         assert_eq!(htlc_success_txn[1].input.len(), 1);
4816         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4817         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4818         assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4819
4820         mine_transaction(&nodes[1], &htlc_timeout_tx);
4821         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4822         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 }]);
4823         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4824         assert!(htlc_updates.update_add_htlcs.is_empty());
4825         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4826         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4827         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4828         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4829         check_added_monitors!(nodes[1], 1);
4830
4831         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4832         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4833         {
4834                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4835         }
4836         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
4837
4838         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4839         mine_transaction(&nodes[1], &htlc_success_txn[1]);
4840         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
4841         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4842         assert!(updates.update_add_htlcs.is_empty());
4843         assert!(updates.update_fail_htlcs.is_empty());
4844         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4845         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
4846         assert!(updates.update_fail_malformed_htlcs.is_empty());
4847         check_added_monitors!(nodes[1], 1);
4848
4849         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4850         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4851
4852         let events = nodes[0].node.get_and_clear_pending_events();
4853         match events[0] {
4854                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4855                         assert_eq!(*payment_preimage, our_payment_preimage);
4856                         assert_eq!(*payment_hash, duplicate_payment_hash);
4857                 }
4858                 _ => panic!("Unexpected event"),
4859         }
4860 }
4861
4862 #[test]
4863 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4864         let chanmon_cfgs = create_chanmon_cfgs(2);
4865         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4866         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4867         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4868
4869         // Create some initial channels
4870         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4871
4872         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
4873         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4874         assert_eq!(local_txn.len(), 1);
4875         assert_eq!(local_txn[0].input.len(), 1);
4876         check_spends!(local_txn[0], chan_1.3);
4877
4878         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4879         nodes[1].node.claim_funds(payment_preimage);
4880         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
4881         check_added_monitors!(nodes[1], 1);
4882
4883         mine_transaction(&nodes[1], &local_txn[0]);
4884         check_added_monitors!(nodes[1], 1);
4885         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4886         let events = nodes[1].node.get_and_clear_pending_msg_events();
4887         match events[0] {
4888                 MessageSendEvent::UpdateHTLCs { .. } => {},
4889                 _ => panic!("Unexpected event"),
4890         }
4891         match events[1] {
4892                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4893                 _ => panic!("Unexepected event"),
4894         }
4895         let node_tx = {
4896                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4897                 assert_eq!(node_txn.len(), 1);
4898                 assert_eq!(node_txn[0].input.len(), 1);
4899                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4900                 check_spends!(node_txn[0], local_txn[0]);
4901                 node_txn[0].clone()
4902         };
4903
4904         mine_transaction(&nodes[1], &node_tx);
4905         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4906
4907         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4908         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4909         assert_eq!(spend_txn.len(), 1);
4910         assert_eq!(spend_txn[0].input.len(), 1);
4911         check_spends!(spend_txn[0], node_tx);
4912         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4913 }
4914
4915 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4916         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4917         // unrevoked commitment transaction.
4918         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4919         // a remote RAA before they could be failed backwards (and combinations thereof).
4920         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4921         // use the same payment hashes.
4922         // Thus, we use a six-node network:
4923         //
4924         // A \         / E
4925         //    - C - D -
4926         // B /         \ F
4927         // And test where C fails back to A/B when D announces its latest commitment transaction
4928         let chanmon_cfgs = create_chanmon_cfgs(6);
4929         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4930         // When this test was written, the default base fee floated based on the HTLC count.
4931         // It is now fixed, so we simply set the fee to the expected value here.
4932         let mut config = test_default_channel_config();
4933         config.channel_config.forwarding_fee_base_msat = 196;
4934         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
4935                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4936         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4937
4938         let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
4939         let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4940         let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
4941         let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
4942         let chan_3_5  = create_announced_chan_between_nodes(&nodes, 3, 5);
4943
4944         // Rebalance and check output sanity...
4945         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
4946         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
4947         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
4948
4949         let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
4950                 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
4951         // 0th HTLC:
4952         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
4953         // 1st HTLC:
4954         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
4955         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4956         // 2nd HTLC:
4957         send_along_route_with_secret(&nodes[1], route.clone(), &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_1, nodes[5].node.create_inbound_payment_for_hash(payment_hash_1, None, 7200, None).unwrap()); // not added < dust limit + HTLC tx fee
4958         // 3rd HTLC:
4959         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_2, nodes[5].node.create_inbound_payment_for_hash(payment_hash_2, None, 7200, None).unwrap()); // not added < dust limit + HTLC tx fee
4960         // 4th HTLC:
4961         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4962         // 5th HTLC:
4963         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4964         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
4965         // 6th HTLC:
4966         send_along_route_with_secret(&nodes[1], route.clone(), &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_3, nodes[5].node.create_inbound_payment_for_hash(payment_hash_3, None, 7200, None).unwrap());
4967         // 7th HTLC:
4968         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_4, nodes[5].node.create_inbound_payment_for_hash(payment_hash_4, None, 7200, None).unwrap());
4969
4970         // 8th HTLC:
4971         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4972         // 9th HTLC:
4973         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4974         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_5, nodes[5].node.create_inbound_payment_for_hash(payment_hash_5, None, 7200, None).unwrap()); // not added < dust limit + HTLC tx fee
4975
4976         // 10th HTLC:
4977         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
4978         // 11th HTLC:
4979         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
4980         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_6, nodes[5].node.create_inbound_payment_for_hash(payment_hash_6, None, 7200, None).unwrap());
4981
4982         // Double-check that six of the new HTLC were added
4983         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
4984         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
4985         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
4986         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
4987
4988         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
4989         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
4990         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
4991         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
4992         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
4993         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
4994         check_added_monitors!(nodes[4], 0);
4995
4996         let failed_destinations = vec![
4997                 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
4998                 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
4999                 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5000                 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5001         ];
5002         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5003         check_added_monitors!(nodes[4], 1);
5004
5005         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5006         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5007         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5008         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5009         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5010         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5011
5012         // Fail 3rd below-dust and 7th above-dust HTLCs
5013         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5014         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5015         check_added_monitors!(nodes[5], 0);
5016
5017         let failed_destinations_2 = vec![
5018                 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5019                 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5020         ];
5021         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5022         check_added_monitors!(nodes[5], 1);
5023
5024         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5025         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5026         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5027         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5028
5029         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5030
5031         // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5032         let failed_destinations_3 = vec![
5033                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5034                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5035                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5036                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5037                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5038                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5039         ];
5040         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5041         check_added_monitors!(nodes[3], 1);
5042         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5043         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5044         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5045         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5046         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5047         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5048         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5049         if deliver_last_raa {
5050                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5051         } else {
5052                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5053         }
5054
5055         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5056         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5057         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5058         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5059         //
5060         // We now broadcast the latest commitment transaction, which *should* result in failures for
5061         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5062         // the non-broadcast above-dust HTLCs.
5063         //
5064         // Alternatively, we may broadcast the previous commitment transaction, which should only
5065         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5066         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5067
5068         if announce_latest {
5069                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5070         } else {
5071                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5072         }
5073         let events = nodes[2].node.get_and_clear_pending_events();
5074         let close_event = if deliver_last_raa {
5075                 assert_eq!(events.len(), 2 + 6);
5076                 events.last().clone().unwrap()
5077         } else {
5078                 assert_eq!(events.len(), 1);
5079                 events.last().clone().unwrap()
5080         };
5081         match close_event {
5082                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5083                 _ => panic!("Unexpected event"),
5084         }
5085
5086         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5087         check_closed_broadcast!(nodes[2], true);
5088         if deliver_last_raa {
5089                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5090
5091                 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();
5092                 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5093         } else {
5094                 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5095                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5096                 } else {
5097                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5098                 };
5099
5100                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5101         }
5102         check_added_monitors!(nodes[2], 3);
5103
5104         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5105         assert_eq!(cs_msgs.len(), 2);
5106         let mut a_done = false;
5107         for msg in cs_msgs {
5108                 match msg {
5109                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5110                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5111                                 // should be failed-backwards here.
5112                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5113                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5114                                         for htlc in &updates.update_fail_htlcs {
5115                                                 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 });
5116                                         }
5117                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5118                                         assert!(!a_done);
5119                                         a_done = true;
5120                                         &nodes[0]
5121                                 } else {
5122                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5123                                         for htlc in &updates.update_fail_htlcs {
5124                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5125                                         }
5126                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5127                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5128                                         &nodes[1]
5129                                 };
5130                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5131                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5132                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5133                                 if announce_latest {
5134                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5135                                         if *node_id == nodes[0].node.get_our_node_id() {
5136                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5137                                         }
5138                                 }
5139                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5140                         },
5141                         _ => panic!("Unexpected event"),
5142                 }
5143         }
5144
5145         let as_events = nodes[0].node.get_and_clear_pending_events();
5146         assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5147         let mut as_failds = HashSet::new();
5148         let mut as_updates = 0;
5149         for event in as_events.iter() {
5150                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5151                         assert!(as_failds.insert(*payment_hash));
5152                         if *payment_hash != payment_hash_2 {
5153                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5154                         } else {
5155                                 assert!(!payment_failed_permanently);
5156                         }
5157                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5158                                 as_updates += 1;
5159                         }
5160                 } else if let &Event::PaymentFailed { .. } = event {
5161                 } else { panic!("Unexpected event"); }
5162         }
5163         assert!(as_failds.contains(&payment_hash_1));
5164         assert!(as_failds.contains(&payment_hash_2));
5165         if announce_latest {
5166                 assert!(as_failds.contains(&payment_hash_3));
5167                 assert!(as_failds.contains(&payment_hash_5));
5168         }
5169         assert!(as_failds.contains(&payment_hash_6));
5170
5171         let bs_events = nodes[1].node.get_and_clear_pending_events();
5172         assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5173         let mut bs_failds = HashSet::new();
5174         let mut bs_updates = 0;
5175         for event in bs_events.iter() {
5176                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5177                         assert!(bs_failds.insert(*payment_hash));
5178                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5179                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5180                         } else {
5181                                 assert!(!payment_failed_permanently);
5182                         }
5183                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5184                                 bs_updates += 1;
5185                         }
5186                 } else if let &Event::PaymentFailed { .. } = event {
5187                 } else { panic!("Unexpected event"); }
5188         }
5189         assert!(bs_failds.contains(&payment_hash_1));
5190         assert!(bs_failds.contains(&payment_hash_2));
5191         if announce_latest {
5192                 assert!(bs_failds.contains(&payment_hash_4));
5193         }
5194         assert!(bs_failds.contains(&payment_hash_5));
5195
5196         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5197         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5198         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5199         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5200         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5201         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5202 }
5203
5204 #[test]
5205 fn test_fail_backwards_latest_remote_announce_a() {
5206         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5207 }
5208
5209 #[test]
5210 fn test_fail_backwards_latest_remote_announce_b() {
5211         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5212 }
5213
5214 #[test]
5215 fn test_fail_backwards_previous_remote_announce() {
5216         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5217         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5218         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5219 }
5220
5221 #[test]
5222 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5223         let chanmon_cfgs = create_chanmon_cfgs(2);
5224         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5225         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5226         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5227
5228         // Create some initial channels
5229         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5230
5231         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5232         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5233         assert_eq!(local_txn[0].input.len(), 1);
5234         check_spends!(local_txn[0], chan_1.3);
5235
5236         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5237         mine_transaction(&nodes[0], &local_txn[0]);
5238         check_closed_broadcast!(nodes[0], true);
5239         check_added_monitors!(nodes[0], 1);
5240         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5241         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5242
5243         let htlc_timeout = {
5244                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5245                 assert_eq!(node_txn.len(), 1);
5246                 assert_eq!(node_txn[0].input.len(), 1);
5247                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5248                 check_spends!(node_txn[0], local_txn[0]);
5249                 node_txn[0].clone()
5250         };
5251
5252         mine_transaction(&nodes[0], &htlc_timeout);
5253         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5254         expect_payment_failed!(nodes[0], our_payment_hash, false);
5255
5256         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5257         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5258         assert_eq!(spend_txn.len(), 3);
5259         check_spends!(spend_txn[0], local_txn[0]);
5260         assert_eq!(spend_txn[1].input.len(), 1);
5261         check_spends!(spend_txn[1], htlc_timeout);
5262         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5263         assert_eq!(spend_txn[2].input.len(), 2);
5264         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5265         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5266                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5267 }
5268
5269 #[test]
5270 fn test_key_derivation_params() {
5271         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5272         // manager rotation to test that `channel_keys_id` returned in
5273         // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5274         // then derive a `delayed_payment_key`.
5275
5276         let chanmon_cfgs = create_chanmon_cfgs(3);
5277
5278         // We manually create the node configuration to backup the seed.
5279         let seed = [42; 32];
5280         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5281         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);
5282         let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5283         let scorer = Mutex::new(test_utils::TestScorer::new());
5284         let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5285         let node = NodeCfg { chain_source: &chanmon_cfgs[0].chain_source, logger: &chanmon_cfgs[0].logger, tx_broadcaster: &chanmon_cfgs[0].tx_broadcaster, fee_estimator: &chanmon_cfgs[0].fee_estimator, router, chain_monitor, keys_manager: &keys_manager, network_graph, node_seed: seed, override_init_features: alloc::rc::Rc::new(core::cell::RefCell::new(None)) };
5286         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5287         node_cfgs.remove(0);
5288         node_cfgs.insert(0, node);
5289
5290         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5291         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5292
5293         // Create some initial channels
5294         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5295         // for node 0
5296         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5297         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5298         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5299
5300         // Ensure all nodes are at the same height
5301         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5302         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5303         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5304         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5305
5306         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5307         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5308         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5309         assert_eq!(local_txn_1[0].input.len(), 1);
5310         check_spends!(local_txn_1[0], chan_1.3);
5311
5312         // We check funding pubkey are unique
5313         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]));
5314         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]));
5315         if from_0_funding_key_0 == from_1_funding_key_0
5316             || from_0_funding_key_0 == from_1_funding_key_1
5317             || from_0_funding_key_1 == from_1_funding_key_0
5318             || from_0_funding_key_1 == from_1_funding_key_1 {
5319                 panic!("Funding pubkeys aren't unique");
5320         }
5321
5322         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5323         mine_transaction(&nodes[0], &local_txn_1[0]);
5324         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5325         check_closed_broadcast!(nodes[0], true);
5326         check_added_monitors!(nodes[0], 1);
5327         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5328
5329         let htlc_timeout = {
5330                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5331                 assert_eq!(node_txn.len(), 1);
5332                 assert_eq!(node_txn[0].input.len(), 1);
5333                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5334                 check_spends!(node_txn[0], local_txn_1[0]);
5335                 node_txn[0].clone()
5336         };
5337
5338         mine_transaction(&nodes[0], &htlc_timeout);
5339         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5340         expect_payment_failed!(nodes[0], our_payment_hash, false);
5341
5342         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5343         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5344         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5345         assert_eq!(spend_txn.len(), 3);
5346         check_spends!(spend_txn[0], local_txn_1[0]);
5347         assert_eq!(spend_txn[1].input.len(), 1);
5348         check_spends!(spend_txn[1], htlc_timeout);
5349         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5350         assert_eq!(spend_txn[2].input.len(), 2);
5351         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5352         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5353                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5354 }
5355
5356 #[test]
5357 fn test_static_output_closing_tx() {
5358         let chanmon_cfgs = create_chanmon_cfgs(2);
5359         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5360         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5361         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5362
5363         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5364
5365         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5366         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5367
5368         mine_transaction(&nodes[0], &closing_tx);
5369         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5370         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5371
5372         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5373         assert_eq!(spend_txn.len(), 1);
5374         check_spends!(spend_txn[0], closing_tx);
5375
5376         mine_transaction(&nodes[1], &closing_tx);
5377         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5378         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5379
5380         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5381         assert_eq!(spend_txn.len(), 1);
5382         check_spends!(spend_txn[0], closing_tx);
5383 }
5384
5385 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5386         let chanmon_cfgs = create_chanmon_cfgs(2);
5387         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5388         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5389         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5390         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5391
5392         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5393
5394         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5395         // present in B's local commitment transaction, but none of A's commitment transactions.
5396         nodes[1].node.claim_funds(payment_preimage);
5397         check_added_monitors!(nodes[1], 1);
5398         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5399
5400         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5401         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5402         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5403
5404         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5405         check_added_monitors!(nodes[0], 1);
5406         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5407         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5408         check_added_monitors!(nodes[1], 1);
5409
5410         let starting_block = nodes[1].best_block_info();
5411         let mut block = Block {
5412                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5413                 txdata: vec![],
5414         };
5415         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5416                 connect_block(&nodes[1], &block);
5417                 block.header.prev_blockhash = block.block_hash();
5418         }
5419         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5420         check_closed_broadcast!(nodes[1], true);
5421         check_added_monitors!(nodes[1], 1);
5422         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5423 }
5424
5425 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5426         let chanmon_cfgs = create_chanmon_cfgs(2);
5427         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5428         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5429         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5430         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5431
5432         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5433         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
5434         check_added_monitors!(nodes[0], 1);
5435
5436         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5437
5438         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5439         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5440         // to "time out" the HTLC.
5441
5442         let starting_block = nodes[1].best_block_info();
5443         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5444
5445         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5446                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5447                 header.prev_blockhash = header.block_hash();
5448         }
5449         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5450         check_closed_broadcast!(nodes[0], true);
5451         check_added_monitors!(nodes[0], 1);
5452         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5453 }
5454
5455 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5456         let chanmon_cfgs = create_chanmon_cfgs(3);
5457         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5458         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5459         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5460         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5461
5462         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5463         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5464         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5465         // actually revoked.
5466         let htlc_value = if use_dust { 50000 } else { 3000000 };
5467         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5468         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5469         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5470         check_added_monitors!(nodes[1], 1);
5471
5472         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5473         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5474         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5475         check_added_monitors!(nodes[0], 1);
5476         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5477         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5478         check_added_monitors!(nodes[1], 1);
5479         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5480         check_added_monitors!(nodes[1], 1);
5481         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5482
5483         if check_revoke_no_close {
5484                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5485                 check_added_monitors!(nodes[0], 1);
5486         }
5487
5488         let starting_block = nodes[1].best_block_info();
5489         let mut block = Block {
5490                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5491                 txdata: vec![],
5492         };
5493         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5494                 connect_block(&nodes[0], &block);
5495                 block.header.prev_blockhash = block.block_hash();
5496         }
5497         if !check_revoke_no_close {
5498                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5499                 check_closed_broadcast!(nodes[0], true);
5500                 check_added_monitors!(nodes[0], 1);
5501                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5502         } else {
5503                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5504         }
5505 }
5506
5507 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5508 // There are only a few cases to test here:
5509 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5510 //    broadcastable commitment transactions result in channel closure,
5511 //  * its included in an unrevoked-but-previous remote commitment transaction,
5512 //  * its included in the latest remote or local commitment transactions.
5513 // We test each of the three possible commitment transactions individually and use both dust and
5514 // non-dust HTLCs.
5515 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5516 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5517 // tested for at least one of the cases in other tests.
5518 #[test]
5519 fn htlc_claim_single_commitment_only_a() {
5520         do_htlc_claim_local_commitment_only(true);
5521         do_htlc_claim_local_commitment_only(false);
5522
5523         do_htlc_claim_current_remote_commitment_only(true);
5524         do_htlc_claim_current_remote_commitment_only(false);
5525 }
5526
5527 #[test]
5528 fn htlc_claim_single_commitment_only_b() {
5529         do_htlc_claim_previous_remote_commitment_only(true, false);
5530         do_htlc_claim_previous_remote_commitment_only(false, false);
5531         do_htlc_claim_previous_remote_commitment_only(true, true);
5532         do_htlc_claim_previous_remote_commitment_only(false, true);
5533 }
5534
5535 #[test]
5536 #[should_panic]
5537 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5538         let chanmon_cfgs = create_chanmon_cfgs(2);
5539         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5540         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5541         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5542         // Force duplicate randomness for every get-random call
5543         for node in nodes.iter() {
5544                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5545         }
5546
5547         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5548         let channel_value_satoshis=10000;
5549         let push_msat=10001;
5550         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5551         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5552         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5553         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5554
5555         // Create a second channel with the same random values. This used to panic due to a colliding
5556         // channel_id, but now panics due to a colliding outbound SCID alias.
5557         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5558 }
5559
5560 #[test]
5561 fn bolt2_open_channel_sending_node_checks_part2() {
5562         let chanmon_cfgs = create_chanmon_cfgs(2);
5563         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5564         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5565         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5566
5567         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5568         let channel_value_satoshis=2^24;
5569         let push_msat=10001;
5570         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5571
5572         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5573         let channel_value_satoshis=10000;
5574         // Test when push_msat is equal to 1000 * funding_satoshis.
5575         let push_msat=1000*channel_value_satoshis+1;
5576         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5577
5578         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5579         let channel_value_satoshis=10000;
5580         let push_msat=10001;
5581         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
5582         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5583         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5584
5585         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5586         // 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
5587         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5588
5589         // 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.
5590         assert!(BREAKDOWN_TIMEOUT>0);
5591         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5592
5593         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5594         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5595         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5596
5597         // 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.
5598         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5599         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5600         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5601         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5602         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5603 }
5604
5605 #[test]
5606 fn bolt2_open_channel_sane_dust_limit() {
5607         let chanmon_cfgs = create_chanmon_cfgs(2);
5608         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5609         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5610         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5611
5612         let channel_value_satoshis=1000000;
5613         let push_msat=10001;
5614         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5615         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5616         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5617         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5618
5619         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5620         let events = nodes[1].node.get_and_clear_pending_msg_events();
5621         let err_msg = match events[0] {
5622                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5623                         msg.clone()
5624                 },
5625                 _ => panic!("Unexpected event"),
5626         };
5627         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5628 }
5629
5630 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5631 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5632 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5633 // is no longer affordable once it's freed.
5634 #[test]
5635 fn test_fail_holding_cell_htlc_upon_free() {
5636         let chanmon_cfgs = create_chanmon_cfgs(2);
5637         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5638         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5639         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5640         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5641
5642         // First nodes[0] generates an update_fee, setting the channel's
5643         // pending_update_fee.
5644         {
5645                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5646                 *feerate_lock += 20;
5647         }
5648         nodes[0].node.timer_tick_occurred();
5649         check_added_monitors!(nodes[0], 1);
5650
5651         let events = nodes[0].node.get_and_clear_pending_msg_events();
5652         assert_eq!(events.len(), 1);
5653         let (update_msg, commitment_signed) = match events[0] {
5654                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5655                         (update_fee.as_ref(), commitment_signed)
5656                 },
5657                 _ => panic!("Unexpected event"),
5658         };
5659
5660         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5661
5662         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5663         let channel_reserve = chan_stat.channel_reserve_msat;
5664         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5665         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5666
5667         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5668         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5669         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5670
5671         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5672         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5673         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5674         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5675
5676         // Flush the pending fee update.
5677         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5678         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5679         check_added_monitors!(nodes[1], 1);
5680         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5681         check_added_monitors!(nodes[0], 1);
5682
5683         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5684         // HTLC, but now that the fee has been raised the payment will now fail, causing
5685         // us to surface its failure to the user.
5686         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5687         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5688         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);
5689         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 {}",
5690                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5691         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5692
5693         // Check that the payment failed to be sent out.
5694         let events = nodes[0].node.get_and_clear_pending_events();
5695         assert_eq!(events.len(), 2);
5696         match &events[0] {
5697                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5698                         assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5699                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5700                         assert_eq!(*payment_failed_permanently, false);
5701                         assert_eq!(*short_channel_id, Some(route.paths[0][0].short_channel_id));
5702                 },
5703                 _ => panic!("Unexpected event"),
5704         }
5705         match &events[1] {
5706                 &Event::PaymentFailed { ref payment_hash, .. } => {
5707                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5708                 },
5709                 _ => panic!("Unexpected event"),
5710         }
5711 }
5712
5713 // Test that if multiple HTLCs are released from the holding cell and one is
5714 // valid but the other is no longer valid upon release, the valid HTLC can be
5715 // successfully completed while the other one fails as expected.
5716 #[test]
5717 fn test_free_and_fail_holding_cell_htlcs() {
5718         let chanmon_cfgs = create_chanmon_cfgs(2);
5719         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5720         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5721         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5722         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5723
5724         // First nodes[0] generates an update_fee, setting the channel's
5725         // pending_update_fee.
5726         {
5727                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5728                 *feerate_lock += 200;
5729         }
5730         nodes[0].node.timer_tick_occurred();
5731         check_added_monitors!(nodes[0], 1);
5732
5733         let events = nodes[0].node.get_and_clear_pending_msg_events();
5734         assert_eq!(events.len(), 1);
5735         let (update_msg, commitment_signed) = match events[0] {
5736                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5737                         (update_fee.as_ref(), commitment_signed)
5738                 },
5739                 _ => panic!("Unexpected event"),
5740         };
5741
5742         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5743
5744         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5745         let channel_reserve = chan_stat.channel_reserve_msat;
5746         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5747         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5748
5749         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5750         let amt_1 = 20000;
5751         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
5752         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5753         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5754
5755         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5756         nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5757         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5758         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5759         let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5760         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2), payment_id_2).unwrap();
5761         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5762         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5763
5764         // Flush the pending fee update.
5765         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5766         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5767         check_added_monitors!(nodes[1], 1);
5768         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5769         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5770         check_added_monitors!(nodes[0], 2);
5771
5772         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5773         // but now that the fee has been raised the second payment will now fail, causing us
5774         // to surface its failure to the user. The first payment should succeed.
5775         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5776         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5777         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);
5778         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 {}",
5779                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5780         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5781
5782         // Check that the second payment failed to be sent out.
5783         let events = nodes[0].node.get_and_clear_pending_events();
5784         assert_eq!(events.len(), 2);
5785         match &events[0] {
5786                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5787                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5788                         assert_eq!(payment_hash_2.clone(), *payment_hash);
5789                         assert_eq!(*payment_failed_permanently, false);
5790                         assert_eq!(*short_channel_id, Some(route_2.paths[0][0].short_channel_id));
5791                 },
5792                 _ => panic!("Unexpected event"),
5793         }
5794         match &events[1] {
5795                 &Event::PaymentFailed { ref payment_hash, .. } => {
5796                         assert_eq!(payment_hash_2.clone(), *payment_hash);
5797                 },
5798                 _ => panic!("Unexpected event"),
5799         }
5800
5801         // Complete the first payment and the RAA from the fee update.
5802         let (payment_event, send_raa_event) = {
5803                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5804                 assert_eq!(msgs.len(), 2);
5805                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5806         };
5807         let raa = match send_raa_event {
5808                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5809                 _ => panic!("Unexpected event"),
5810         };
5811         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5812         check_added_monitors!(nodes[1], 1);
5813         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5814         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5815         let events = nodes[1].node.get_and_clear_pending_events();
5816         assert_eq!(events.len(), 1);
5817         match events[0] {
5818                 Event::PendingHTLCsForwardable { .. } => {},
5819                 _ => panic!("Unexpected event"),
5820         }
5821         nodes[1].node.process_pending_htlc_forwards();
5822         let events = nodes[1].node.get_and_clear_pending_events();
5823         assert_eq!(events.len(), 1);
5824         match events[0] {
5825                 Event::PaymentClaimable { .. } => {},
5826                 _ => panic!("Unexpected event"),
5827         }
5828         nodes[1].node.claim_funds(payment_preimage_1);
5829         check_added_monitors!(nodes[1], 1);
5830         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5831
5832         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5833         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5834         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5835         expect_payment_sent!(nodes[0], payment_preimage_1);
5836 }
5837
5838 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
5839 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
5840 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
5841 // once it's freed.
5842 #[test]
5843 fn test_fail_holding_cell_htlc_upon_free_multihop() {
5844         let chanmon_cfgs = create_chanmon_cfgs(3);
5845         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5846         // When this test was written, the default base fee floated based on the HTLC count.
5847         // It is now fixed, so we simply set the fee to the expected value here.
5848         let mut config = test_default_channel_config();
5849         config.channel_config.forwarding_fee_base_msat = 196;
5850         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5851         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5852         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5853         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
5854
5855         // First nodes[1] generates an update_fee, setting the channel's
5856         // pending_update_fee.
5857         {
5858                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
5859                 *feerate_lock += 20;
5860         }
5861         nodes[1].node.timer_tick_occurred();
5862         check_added_monitors!(nodes[1], 1);
5863
5864         let events = nodes[1].node.get_and_clear_pending_msg_events();
5865         assert_eq!(events.len(), 1);
5866         let (update_msg, commitment_signed) = match events[0] {
5867                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5868                         (update_fee.as_ref(), commitment_signed)
5869                 },
5870                 _ => panic!("Unexpected event"),
5871         };
5872
5873         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
5874
5875         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
5876         let channel_reserve = chan_stat.channel_reserve_msat;
5877         let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
5878         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_0_1.2);
5879
5880         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5881         let feemsat = 239;
5882         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
5883         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
5884         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
5885         let payment_event = {
5886                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5887                 check_added_monitors!(nodes[0], 1);
5888
5889                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5890                 assert_eq!(events.len(), 1);
5891
5892                 SendEvent::from_event(events.remove(0))
5893         };
5894         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5895         check_added_monitors!(nodes[1], 0);
5896         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5897         expect_pending_htlcs_forwardable!(nodes[1]);
5898
5899         chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
5900         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5901
5902         // Flush the pending fee update.
5903         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
5904         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5905         check_added_monitors!(nodes[2], 1);
5906         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
5907         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
5908         check_added_monitors!(nodes[1], 2);
5909
5910         // A final RAA message is generated to finalize the fee update.
5911         let events = nodes[1].node.get_and_clear_pending_msg_events();
5912         assert_eq!(events.len(), 1);
5913
5914         let raa_msg = match &events[0] {
5915                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
5916                         msg.clone()
5917                 },
5918                 _ => panic!("Unexpected event"),
5919         };
5920
5921         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
5922         check_added_monitors!(nodes[2], 1);
5923         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
5924
5925         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
5926         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
5927         assert_eq!(process_htlc_forwards_event.len(), 2);
5928         match &process_htlc_forwards_event[0] {
5929                 &Event::PendingHTLCsForwardable { .. } => {},
5930                 _ => panic!("Unexpected event"),
5931         }
5932
5933         // In response, we call ChannelManager's process_pending_htlc_forwards
5934         nodes[1].node.process_pending_htlc_forwards();
5935         check_added_monitors!(nodes[1], 1);
5936
5937         // This causes the HTLC to be failed backwards.
5938         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
5939         assert_eq!(fail_event.len(), 1);
5940         let (fail_msg, commitment_signed) = match &fail_event[0] {
5941                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
5942                         assert_eq!(updates.update_add_htlcs.len(), 0);
5943                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
5944                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
5945                         assert_eq!(updates.update_fail_htlcs.len(), 1);
5946                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
5947                 },
5948                 _ => panic!("Unexpected event"),
5949         };
5950
5951         // Pass the failure messages back to nodes[0].
5952         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5953         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5954
5955         // Complete the HTLC failure+removal process.
5956         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5957         check_added_monitors!(nodes[0], 1);
5958         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5959         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
5960         check_added_monitors!(nodes[1], 2);
5961         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
5962         assert_eq!(final_raa_event.len(), 1);
5963         let raa = match &final_raa_event[0] {
5964                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
5965                 _ => panic!("Unexpected event"),
5966         };
5967         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
5968         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
5969         check_added_monitors!(nodes[0], 1);
5970 }
5971
5972 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
5973 // 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.
5974 //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.
5975
5976 #[test]
5977 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
5978         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
5979         let chanmon_cfgs = create_chanmon_cfgs(2);
5980         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5981         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5982         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5983         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5984
5985         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
5986         route.paths[0][0].fee_msat = 100;
5987
5988         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 },
5989                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
5990         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5991         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send less than their minimum HTLC value", 1);
5992 }
5993
5994 #[test]
5995 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
5996         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
5997         let chanmon_cfgs = create_chanmon_cfgs(2);
5998         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5999         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6000         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6001         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6002
6003         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6004         route.paths[0][0].fee_msat = 0;
6005         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 },
6006                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6007
6008         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6009         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6010 }
6011
6012 #[test]
6013 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6014         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6015         let chanmon_cfgs = create_chanmon_cfgs(2);
6016         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6017         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6018         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6019         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6020
6021         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6022         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6023         check_added_monitors!(nodes[0], 1);
6024         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6025         updates.update_add_htlcs[0].amount_msat = 0;
6026
6027         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6028         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6029         check_closed_broadcast!(nodes[1], true).unwrap();
6030         check_added_monitors!(nodes[1], 1);
6031         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6032 }
6033
6034 #[test]
6035 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6036         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6037         //It is enforced when constructing a route.
6038         let chanmon_cfgs = create_chanmon_cfgs(2);
6039         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6040         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6041         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6042         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6043
6044         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6045                 .with_features(nodes[1].node.invoice_features());
6046         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6047         route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6048         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::InvalidRoute { ref err },
6049                 assert_eq!(err, &"Channel CLTV overflowed?"));
6050 }
6051
6052 #[test]
6053 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6054         //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.
6055         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6056         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6057         let chanmon_cfgs = create_chanmon_cfgs(2);
6058         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6059         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6060         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6061         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6062         let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6063                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6064
6065         for i in 0..max_accepted_htlcs {
6066                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6067                 let payment_event = {
6068                         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6069                         check_added_monitors!(nodes[0], 1);
6070
6071                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6072                         assert_eq!(events.len(), 1);
6073                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6074                                 assert_eq!(htlcs[0].htlc_id, i);
6075                         } else {
6076                                 assert!(false);
6077                         }
6078                         SendEvent::from_event(events.remove(0))
6079                 };
6080                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6081                 check_added_monitors!(nodes[1], 0);
6082                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6083
6084                 expect_pending_htlcs_forwardable!(nodes[1]);
6085                 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6086         }
6087         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6088         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 },
6089                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6090
6091         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6092         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
6093 }
6094
6095 #[test]
6096 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6097         //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.
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 channel_value = 100000;
6103         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6104         let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6105
6106         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6107
6108         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6109         // Manually create a route over our max in flight (which our router normally automatically
6110         // limits us to.
6111         route.paths[0][0].fee_msat =  max_in_flight + 1;
6112         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 },
6113                 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)));
6114
6115         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6116         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put us over the max HTLC value in flight our peer will accept", 1);
6117
6118         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6119 }
6120
6121 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6122 #[test]
6123 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6124         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6125         let chanmon_cfgs = create_chanmon_cfgs(2);
6126         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6127         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6128         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6129         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6130         let htlc_minimum_msat: u64;
6131         {
6132                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6133                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6134                 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6135                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6136         }
6137
6138         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6139         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6140         check_added_monitors!(nodes[0], 1);
6141         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6142         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6143         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6144         assert!(nodes[1].node.list_channels().is_empty());
6145         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6146         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()));
6147         check_added_monitors!(nodes[1], 1);
6148         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6149 }
6150
6151 #[test]
6152 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6153         //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
6154         let chanmon_cfgs = create_chanmon_cfgs(2);
6155         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6156         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6157         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6158         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6159
6160         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6161         let channel_reserve = chan_stat.channel_reserve_msat;
6162         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6163         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
6164         // The 2* and +1 are for the fee spike reserve.
6165         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6166
6167         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6168         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6169         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6170         check_added_monitors!(nodes[0], 1);
6171         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6172
6173         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6174         // at this time channel-initiatee receivers are not required to enforce that senders
6175         // respect the fee_spike_reserve.
6176         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6177         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6178
6179         assert!(nodes[1].node.list_channels().is_empty());
6180         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6181         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6182         check_added_monitors!(nodes[1], 1);
6183         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6184 }
6185
6186 #[test]
6187 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6188         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6189         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6190         let chanmon_cfgs = create_chanmon_cfgs(2);
6191         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6192         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6193         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6194         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6195
6196         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6197         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6198         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6199         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6200         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6201         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6202
6203         let mut msg = msgs::UpdateAddHTLC {
6204                 channel_id: chan.2,
6205                 htlc_id: 0,
6206                 amount_msat: 1000,
6207                 payment_hash: our_payment_hash,
6208                 cltv_expiry: htlc_cltv,
6209                 onion_routing_packet: onion_packet.clone(),
6210         };
6211
6212         for i in 0..super::channel::OUR_MAX_HTLCS {
6213                 msg.htlc_id = i as u64;
6214                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6215         }
6216         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6217         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6218
6219         assert!(nodes[1].node.list_channels().is_empty());
6220         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6221         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6222         check_added_monitors!(nodes[1], 1);
6223         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6224 }
6225
6226 #[test]
6227 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6228         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6229         let chanmon_cfgs = create_chanmon_cfgs(2);
6230         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6231         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6232         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6233         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6234
6235         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6236         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6237         check_added_monitors!(nodes[0], 1);
6238         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6239         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6240         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6241
6242         assert!(nodes[1].node.list_channels().is_empty());
6243         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6244         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6245         check_added_monitors!(nodes[1], 1);
6246         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6247 }
6248
6249 #[test]
6250 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6251         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6252         let chanmon_cfgs = create_chanmon_cfgs(2);
6253         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6254         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6255         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6256
6257         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6258         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6259         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6260         check_added_monitors!(nodes[0], 1);
6261         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6262         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6263         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6264
6265         assert!(nodes[1].node.list_channels().is_empty());
6266         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6267         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6268         check_added_monitors!(nodes[1], 1);
6269         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6270 }
6271
6272 #[test]
6273 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6274         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6275         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6276         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6277         let chanmon_cfgs = create_chanmon_cfgs(2);
6278         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6279         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6280         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6281
6282         create_announced_chan_between_nodes(&nodes, 0, 1);
6283         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6284         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6285         check_added_monitors!(nodes[0], 1);
6286         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6287         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6288
6289         //Disconnect and Reconnect
6290         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6291         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6292         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }, true).unwrap();
6293         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6294         assert_eq!(reestablish_1.len(), 1);
6295         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }, false).unwrap();
6296         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6297         assert_eq!(reestablish_2.len(), 1);
6298         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6299         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6300         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6301         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6302
6303         //Resend HTLC
6304         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6305         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6306         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6307         check_added_monitors!(nodes[1], 1);
6308         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6309
6310         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6311
6312         assert!(nodes[1].node.list_channels().is_empty());
6313         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6314         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6315         check_added_monitors!(nodes[1], 1);
6316         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6317 }
6318
6319 #[test]
6320 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6321         //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.
6322
6323         let chanmon_cfgs = create_chanmon_cfgs(2);
6324         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6325         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6326         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6327         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6328         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6329         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6330
6331         check_added_monitors!(nodes[0], 1);
6332         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6333         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6334
6335         let update_msg = msgs::UpdateFulfillHTLC{
6336                 channel_id: chan.2,
6337                 htlc_id: 0,
6338                 payment_preimage: our_payment_preimage,
6339         };
6340
6341         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6342
6343         assert!(nodes[0].node.list_channels().is_empty());
6344         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6345         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()));
6346         check_added_monitors!(nodes[0], 1);
6347         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6348 }
6349
6350 #[test]
6351 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6352         //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.
6353
6354         let chanmon_cfgs = create_chanmon_cfgs(2);
6355         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6356         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6357         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6358         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6359
6360         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6361         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6362         check_added_monitors!(nodes[0], 1);
6363         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6364         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6365
6366         let update_msg = msgs::UpdateFailHTLC{
6367                 channel_id: chan.2,
6368                 htlc_id: 0,
6369                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6370         };
6371
6372         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6373
6374         assert!(nodes[0].node.list_channels().is_empty());
6375         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6376         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()));
6377         check_added_monitors!(nodes[0], 1);
6378         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6379 }
6380
6381 #[test]
6382 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6383         //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.
6384
6385         let chanmon_cfgs = create_chanmon_cfgs(2);
6386         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6387         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6388         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6389         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6390
6391         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6392         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6393         check_added_monitors!(nodes[0], 1);
6394         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6395         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6396         let update_msg = msgs::UpdateFailMalformedHTLC{
6397                 channel_id: chan.2,
6398                 htlc_id: 0,
6399                 sha256_of_onion: [1; 32],
6400                 failure_code: 0x8000,
6401         };
6402
6403         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6404
6405         assert!(nodes[0].node.list_channels().is_empty());
6406         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6407         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()));
6408         check_added_monitors!(nodes[0], 1);
6409         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6410 }
6411
6412 #[test]
6413 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6414         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6415
6416         let chanmon_cfgs = create_chanmon_cfgs(2);
6417         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6418         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6419         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6420         create_announced_chan_between_nodes(&nodes, 0, 1);
6421
6422         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6423
6424         nodes[1].node.claim_funds(our_payment_preimage);
6425         check_added_monitors!(nodes[1], 1);
6426         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6427
6428         let events = nodes[1].node.get_and_clear_pending_msg_events();
6429         assert_eq!(events.len(), 1);
6430         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6431                 match events[0] {
6432                         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, .. } } => {
6433                                 assert!(update_add_htlcs.is_empty());
6434                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6435                                 assert!(update_fail_htlcs.is_empty());
6436                                 assert!(update_fail_malformed_htlcs.is_empty());
6437                                 assert!(update_fee.is_none());
6438                                 update_fulfill_htlcs[0].clone()
6439                         },
6440                         _ => panic!("Unexpected event"),
6441                 }
6442         };
6443
6444         update_fulfill_msg.htlc_id = 1;
6445
6446         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6447
6448         assert!(nodes[0].node.list_channels().is_empty());
6449         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6450         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6451         check_added_monitors!(nodes[0], 1);
6452         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6453 }
6454
6455 #[test]
6456 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6457         //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.
6458
6459         let chanmon_cfgs = create_chanmon_cfgs(2);
6460         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6461         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6462         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6463         create_announced_chan_between_nodes(&nodes, 0, 1);
6464
6465         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6466
6467         nodes[1].node.claim_funds(our_payment_preimage);
6468         check_added_monitors!(nodes[1], 1);
6469         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6470
6471         let events = nodes[1].node.get_and_clear_pending_msg_events();
6472         assert_eq!(events.len(), 1);
6473         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6474                 match events[0] {
6475                         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, .. } } => {
6476                                 assert!(update_add_htlcs.is_empty());
6477                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6478                                 assert!(update_fail_htlcs.is_empty());
6479                                 assert!(update_fail_malformed_htlcs.is_empty());
6480                                 assert!(update_fee.is_none());
6481                                 update_fulfill_htlcs[0].clone()
6482                         },
6483                         _ => panic!("Unexpected event"),
6484                 }
6485         };
6486
6487         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6488
6489         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6490
6491         assert!(nodes[0].node.list_channels().is_empty());
6492         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6493         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6494         check_added_monitors!(nodes[0], 1);
6495         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6496 }
6497
6498 #[test]
6499 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6500         //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.
6501
6502         let chanmon_cfgs = create_chanmon_cfgs(2);
6503         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6504         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6505         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6506         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6507
6508         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6509         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6510         check_added_monitors!(nodes[0], 1);
6511
6512         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6513         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6514
6515         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6516         check_added_monitors!(nodes[1], 0);
6517         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6518
6519         let events = nodes[1].node.get_and_clear_pending_msg_events();
6520
6521         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6522                 match events[0] {
6523                         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, .. } } => {
6524                                 assert!(update_add_htlcs.is_empty());
6525                                 assert!(update_fulfill_htlcs.is_empty());
6526                                 assert!(update_fail_htlcs.is_empty());
6527                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6528                                 assert!(update_fee.is_none());
6529                                 update_fail_malformed_htlcs[0].clone()
6530                         },
6531                         _ => panic!("Unexpected event"),
6532                 }
6533         };
6534         update_msg.failure_code &= !0x8000;
6535         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6536
6537         assert!(nodes[0].node.list_channels().is_empty());
6538         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6539         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6540         check_added_monitors!(nodes[0], 1);
6541         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6542 }
6543
6544 #[test]
6545 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6546         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6547         //    * 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.
6548
6549         let chanmon_cfgs = create_chanmon_cfgs(3);
6550         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6551         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6552         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6553         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6554         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6555
6556         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6557
6558         //First hop
6559         let mut payment_event = {
6560                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6561                 check_added_monitors!(nodes[0], 1);
6562                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6563                 assert_eq!(events.len(), 1);
6564                 SendEvent::from_event(events.remove(0))
6565         };
6566         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6567         check_added_monitors!(nodes[1], 0);
6568         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6569         expect_pending_htlcs_forwardable!(nodes[1]);
6570         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6571         assert_eq!(events_2.len(), 1);
6572         check_added_monitors!(nodes[1], 1);
6573         payment_event = SendEvent::from_event(events_2.remove(0));
6574         assert_eq!(payment_event.msgs.len(), 1);
6575
6576         //Second Hop
6577         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6578         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6579         check_added_monitors!(nodes[2], 0);
6580         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6581
6582         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6583         assert_eq!(events_3.len(), 1);
6584         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6585                 match events_3[0] {
6586                         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 } } => {
6587                                 assert!(update_add_htlcs.is_empty());
6588                                 assert!(update_fulfill_htlcs.is_empty());
6589                                 assert!(update_fail_htlcs.is_empty());
6590                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6591                                 assert!(update_fee.is_none());
6592                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6593                         },
6594                         _ => panic!("Unexpected event"),
6595                 }
6596         };
6597
6598         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6599
6600         check_added_monitors!(nodes[1], 0);
6601         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6602         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 }]);
6603         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6604         assert_eq!(events_4.len(), 1);
6605
6606         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6607         match events_4[0] {
6608                 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, .. } } => {
6609                         assert!(update_add_htlcs.is_empty());
6610                         assert!(update_fulfill_htlcs.is_empty());
6611                         assert_eq!(update_fail_htlcs.len(), 1);
6612                         assert!(update_fail_malformed_htlcs.is_empty());
6613                         assert!(update_fee.is_none());
6614                 },
6615                 _ => panic!("Unexpected event"),
6616         };
6617
6618         check_added_monitors!(nodes[1], 1);
6619 }
6620
6621 #[test]
6622 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6623         let chanmon_cfgs = create_chanmon_cfgs(3);
6624         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6625         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6626         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6627         create_announced_chan_between_nodes(&nodes, 0, 1);
6628         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6629
6630         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6631
6632         // First hop
6633         let mut payment_event = {
6634                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6635                 check_added_monitors!(nodes[0], 1);
6636                 SendEvent::from_node(&nodes[0])
6637         };
6638
6639         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6640         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6641         expect_pending_htlcs_forwardable!(nodes[1]);
6642         check_added_monitors!(nodes[1], 1);
6643         payment_event = SendEvent::from_node(&nodes[1]);
6644         assert_eq!(payment_event.msgs.len(), 1);
6645
6646         // Second Hop
6647         payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6648         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6649         check_added_monitors!(nodes[2], 0);
6650         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6651
6652         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6653         assert_eq!(events_3.len(), 1);
6654         match events_3[0] {
6655                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6656                         let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6657                         // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6658                         update_msg.failure_code |= 0x2000;
6659
6660                         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6661                         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6662                 },
6663                 _ => panic!("Unexpected event"),
6664         }
6665
6666         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6667                 vec![HTLCDestination::NextHopChannel {
6668                         node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6669         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6670         assert_eq!(events_4.len(), 1);
6671         check_added_monitors!(nodes[1], 1);
6672
6673         match events_4[0] {
6674                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6675                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6676                         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6677                 },
6678                 _ => panic!("Unexpected event"),
6679         }
6680
6681         let events_5 = nodes[0].node.get_and_clear_pending_events();
6682         assert_eq!(events_5.len(), 2);
6683
6684         // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6685         // the node originating the error to its next hop.
6686         match events_5[0] {
6687                 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6688                 } => {
6689                         assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6690                         assert!(is_permanent);
6691                         assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6692                 },
6693                 _ => panic!("Unexpected event"),
6694         }
6695         match events_5[1] {
6696                 Event::PaymentFailed { payment_hash, .. } => {
6697                         assert_eq!(payment_hash, our_payment_hash);
6698                 },
6699                 _ => panic!("Unexpected event"),
6700         }
6701
6702         // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6703 }
6704
6705 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6706         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6707         // 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
6708         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6709
6710         let mut chanmon_cfgs = create_chanmon_cfgs(2);
6711         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6712         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6713         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6714         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6715         let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
6716
6717         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6718                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6719
6720         // We route 2 dust-HTLCs between A and B
6721         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6722         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6723         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6724
6725         // Cache one local commitment tx as previous
6726         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6727
6728         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6729         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6730         check_added_monitors!(nodes[1], 0);
6731         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6732         check_added_monitors!(nodes[1], 1);
6733
6734         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6735         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6736         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6737         check_added_monitors!(nodes[0], 1);
6738
6739         // Cache one local commitment tx as lastest
6740         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6741
6742         let events = nodes[0].node.get_and_clear_pending_msg_events();
6743         match events[0] {
6744                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6745                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6746                 },
6747                 _ => panic!("Unexpected event"),
6748         }
6749         match events[1] {
6750                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6751                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6752                 },
6753                 _ => panic!("Unexpected event"),
6754         }
6755
6756         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6757         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6758         if announce_latest {
6759                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6760         } else {
6761                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6762         }
6763
6764         check_closed_broadcast!(nodes[0], true);
6765         check_added_monitors!(nodes[0], 1);
6766         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6767
6768         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6769         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6770         let events = nodes[0].node.get_and_clear_pending_events();
6771         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6772         assert_eq!(events.len(), 4);
6773         let mut first_failed = false;
6774         for event in events {
6775                 match event {
6776                         Event::PaymentPathFailed { payment_hash, .. } => {
6777                                 if payment_hash == payment_hash_1 {
6778                                         assert!(!first_failed);
6779                                         first_failed = true;
6780                                 } else {
6781                                         assert_eq!(payment_hash, payment_hash_2);
6782                                 }
6783                         },
6784                         Event::PaymentFailed { .. } => {}
6785                         _ => panic!("Unexpected event"),
6786                 }
6787         }
6788 }
6789
6790 #[test]
6791 fn test_failure_delay_dust_htlc_local_commitment() {
6792         do_test_failure_delay_dust_htlc_local_commitment(true);
6793         do_test_failure_delay_dust_htlc_local_commitment(false);
6794 }
6795
6796 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6797         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6798         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6799         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6800         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6801         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6802         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6803
6804         let chanmon_cfgs = create_chanmon_cfgs(3);
6805         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6806         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6807         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6808         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6809
6810         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6811                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6812
6813         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6814         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6815
6816         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6817         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6818
6819         // We revoked bs_commitment_tx
6820         if revoked {
6821                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6822                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6823         }
6824
6825         let mut timeout_tx = Vec::new();
6826         if local {
6827                 // We fail dust-HTLC 1 by broadcast of local commitment tx
6828                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
6829                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6830                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6831                 expect_payment_failed!(nodes[0], dust_hash, false);
6832
6833                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
6834                 check_closed_broadcast!(nodes[0], true);
6835                 check_added_monitors!(nodes[0], 1);
6836                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6837                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6838                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6839                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6840                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6841                 mine_transaction(&nodes[0], &timeout_tx[0]);
6842                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6843                 expect_payment_failed!(nodes[0], non_dust_hash, false);
6844         } else {
6845                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6846                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
6847                 check_closed_broadcast!(nodes[0], true);
6848                 check_added_monitors!(nodes[0], 1);
6849                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6850                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6851
6852                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
6853                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
6854                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
6855                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
6856                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
6857                 // dust HTLC should have been failed.
6858                 expect_payment_failed!(nodes[0], dust_hash, false);
6859
6860                 if !revoked {
6861                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6862                 } else {
6863                         assert_eq!(timeout_tx[0].lock_time.0, 0);
6864                 }
6865                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
6866                 mine_transaction(&nodes[0], &timeout_tx[0]);
6867                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6868                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6869                 expect_payment_failed!(nodes[0], non_dust_hash, false);
6870         }
6871 }
6872
6873 #[test]
6874 fn test_sweep_outbound_htlc_failure_update() {
6875         do_test_sweep_outbound_htlc_failure_update(false, true);
6876         do_test_sweep_outbound_htlc_failure_update(false, false);
6877         do_test_sweep_outbound_htlc_failure_update(true, false);
6878 }
6879
6880 #[test]
6881 fn test_user_configurable_csv_delay() {
6882         // We test our channel constructors yield errors when we pass them absurd csv delay
6883
6884         let mut low_our_to_self_config = UserConfig::default();
6885         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
6886         let mut high_their_to_self_config = UserConfig::default();
6887         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
6888         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6889         let chanmon_cfgs = create_chanmon_cfgs(2);
6890         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6891         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6892         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6893
6894         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6895         if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6896                 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
6897                 &low_our_to_self_config, 0, 42)
6898         {
6899                 match error {
6900                         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())); },
6901                         _ => panic!("Unexpected event"),
6902                 }
6903         } else { assert!(false) }
6904
6905         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6906         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6907         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6908         open_channel.to_self_delay = 200;
6909         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6910                 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[0].node.channel_type_features(), &nodes[1].node.init_features(), &open_channel, 0,
6911                 &low_our_to_self_config, 0, &nodes[0].logger, 42)
6912         {
6913                 match error {
6914                         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()));  },
6915                         _ => panic!("Unexpected event"),
6916                 }
6917         } else { assert!(false); }
6918
6919         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6920         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6921         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
6922         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6923         accept_channel.to_self_delay = 200;
6924         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
6925         let reason_msg;
6926         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
6927                 match action {
6928                         &ErrorAction::SendErrorMessage { ref msg } => {
6929                                 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()));
6930                                 reason_msg = msg.data.clone();
6931                         },
6932                         _ => { panic!(); }
6933                 }
6934         } else { panic!(); }
6935         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
6936
6937         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
6938         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6939         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6940         open_channel.to_self_delay = 200;
6941         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6942                 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[0].node.channel_type_features(), &nodes[1].node.init_features(), &open_channel, 0,
6943                 &high_their_to_self_config, 0, &nodes[0].logger, 42)
6944         {
6945                 match error {
6946                         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())); },
6947                         _ => panic!("Unexpected event"),
6948                 }
6949         } else { assert!(false); }
6950 }
6951
6952 #[test]
6953 fn test_check_htlc_underpaying() {
6954         // Send payment through A -> B but A is maliciously
6955         // sending a probe payment (i.e less than expected value0
6956         // to B, B should refuse payment.
6957
6958         let chanmon_cfgs = create_chanmon_cfgs(2);
6959         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6960         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6961         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6962
6963         // Create some initial channels
6964         create_announced_chan_between_nodes(&nodes, 0, 1);
6965
6966         let scorer = test_utils::TestScorer::new();
6967         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
6968         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV).with_features(nodes[1].node.invoice_features());
6969         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();
6970         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
6971         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
6972         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6973         check_added_monitors!(nodes[0], 1);
6974
6975         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6976         assert_eq!(events.len(), 1);
6977         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
6978         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6979         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6980
6981         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
6982         // and then will wait a second random delay before failing the HTLC back:
6983         expect_pending_htlcs_forwardable!(nodes[1]);
6984         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
6985
6986         // Node 3 is expecting payment of 100_000 but received 10_000,
6987         // it should fail htlc like we didn't know the preimage.
6988         nodes[1].node.process_pending_htlc_forwards();
6989
6990         let events = nodes[1].node.get_and_clear_pending_msg_events();
6991         assert_eq!(events.len(), 1);
6992         let (update_fail_htlc, commitment_signed) = match events[0] {
6993                 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 } } => {
6994                         assert!(update_add_htlcs.is_empty());
6995                         assert!(update_fulfill_htlcs.is_empty());
6996                         assert_eq!(update_fail_htlcs.len(), 1);
6997                         assert!(update_fail_malformed_htlcs.is_empty());
6998                         assert!(update_fee.is_none());
6999                         (update_fail_htlcs[0].clone(), commitment_signed)
7000                 },
7001                 _ => panic!("Unexpected event"),
7002         };
7003         check_added_monitors!(nodes[1], 1);
7004
7005         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7006         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7007
7008         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7009         let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7010         expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7011         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7012 }
7013
7014 #[test]
7015 fn test_announce_disable_channels() {
7016         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7017         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7018
7019         let chanmon_cfgs = create_chanmon_cfgs(2);
7020         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7021         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7022         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7023
7024         create_announced_chan_between_nodes(&nodes, 0, 1);
7025         create_announced_chan_between_nodes(&nodes, 1, 0);
7026         create_announced_chan_between_nodes(&nodes, 0, 1);
7027
7028         // Disconnect peers
7029         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7030         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7031
7032         nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7033         nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7034         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7035         assert_eq!(msg_events.len(), 3);
7036         let mut chans_disabled = HashMap::new();
7037         for e in msg_events {
7038                 match e {
7039                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7040                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7041                                 // Check that each channel gets updated exactly once
7042                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7043                                         panic!("Generated ChannelUpdate for wrong chan!");
7044                                 }
7045                         },
7046                         _ => panic!("Unexpected event"),
7047                 }
7048         }
7049         // Reconnect peers
7050         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }, true).unwrap();
7051         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7052         assert_eq!(reestablish_1.len(), 3);
7053         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }, false).unwrap();
7054         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7055         assert_eq!(reestablish_2.len(), 3);
7056
7057         // Reestablish chan_1
7058         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7059         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7060         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7061         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7062         // Reestablish chan_2
7063         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7064         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7065         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7066         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7067         // Reestablish chan_3
7068         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7069         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7070         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7071         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7072
7073         nodes[0].node.timer_tick_occurred();
7074         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7075         nodes[0].node.timer_tick_occurred();
7076         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7077         assert_eq!(msg_events.len(), 3);
7078         for e in msg_events {
7079                 match e {
7080                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7081                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7082                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7083                                         // Each update should have a higher timestamp than the previous one, replacing
7084                                         // the old one.
7085                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7086                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7087                                 }
7088                         },
7089                         _ => panic!("Unexpected event"),
7090                 }
7091         }
7092         // Check that each channel gets updated exactly once
7093         assert!(chans_disabled.is_empty());
7094 }
7095
7096 #[test]
7097 fn test_bump_penalty_txn_on_revoked_commitment() {
7098         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7099         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7100
7101         let chanmon_cfgs = create_chanmon_cfgs(2);
7102         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7103         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7104         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7105
7106         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7107
7108         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7109         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7110                 .with_features(nodes[0].node.invoice_features());
7111         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7112         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7113
7114         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7115         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7116         assert_eq!(revoked_txn[0].output.len(), 4);
7117         assert_eq!(revoked_txn[0].input.len(), 1);
7118         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7119         let revoked_txid = revoked_txn[0].txid();
7120
7121         let mut penalty_sum = 0;
7122         for outp in revoked_txn[0].output.iter() {
7123                 if outp.script_pubkey.is_v0_p2wsh() {
7124                         penalty_sum += outp.value;
7125                 }
7126         }
7127
7128         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7129         let header_114 = connect_blocks(&nodes[1], 14);
7130
7131         // Actually revoke tx by claiming a HTLC
7132         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7133         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7134         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7135         check_added_monitors!(nodes[1], 1);
7136
7137         // One or more justice tx should have been broadcast, check it
7138         let penalty_1;
7139         let feerate_1;
7140         {
7141                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7142                 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7143                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7144                 assert_eq!(node_txn[0].output.len(), 1);
7145                 check_spends!(node_txn[0], revoked_txn[0]);
7146                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7147                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7148                 penalty_1 = node_txn[0].txid();
7149                 node_txn.clear();
7150         };
7151
7152         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7153         connect_blocks(&nodes[1], 15);
7154         let mut penalty_2 = penalty_1;
7155         let mut feerate_2 = 0;
7156         {
7157                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7158                 assert_eq!(node_txn.len(), 1);
7159                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7160                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7161                         assert_eq!(node_txn[0].output.len(), 1);
7162                         check_spends!(node_txn[0], revoked_txn[0]);
7163                         penalty_2 = node_txn[0].txid();
7164                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7165                         assert_ne!(penalty_2, penalty_1);
7166                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7167                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7168                         // Verify 25% bump heuristic
7169                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7170                         node_txn.clear();
7171                 }
7172         }
7173         assert_ne!(feerate_2, 0);
7174
7175         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7176         connect_blocks(&nodes[1], 1);
7177         let penalty_3;
7178         let mut feerate_3 = 0;
7179         {
7180                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7181                 assert_eq!(node_txn.len(), 1);
7182                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7183                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7184                         assert_eq!(node_txn[0].output.len(), 1);
7185                         check_spends!(node_txn[0], revoked_txn[0]);
7186                         penalty_3 = node_txn[0].txid();
7187                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7188                         assert_ne!(penalty_3, penalty_2);
7189                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7190                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7191                         // Verify 25% bump heuristic
7192                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7193                         node_txn.clear();
7194                 }
7195         }
7196         assert_ne!(feerate_3, 0);
7197
7198         nodes[1].node.get_and_clear_pending_events();
7199         nodes[1].node.get_and_clear_pending_msg_events();
7200 }
7201
7202 #[test]
7203 fn test_bump_penalty_txn_on_revoked_htlcs() {
7204         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7205         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7206
7207         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7208         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7209         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7210         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7211         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7212
7213         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7214         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7215         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_features(nodes[1].node.invoice_features());
7216         let scorer = test_utils::TestScorer::new();
7217         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7218         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7219                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7220         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7221         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_features(nodes[0].node.invoice_features());
7222         let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7223                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7224         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7225
7226         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7227         assert_eq!(revoked_local_txn[0].input.len(), 1);
7228         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7229
7230         // Revoke local commitment tx
7231         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7232
7233         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7234         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7235         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7236         check_closed_broadcast!(nodes[1], true);
7237         check_added_monitors!(nodes[1], 1);
7238         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7239         connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7240
7241         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
7242         assert_eq!(revoked_htlc_txn.len(), 2);
7243
7244         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7245         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7246         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7247
7248         assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7249         assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7250         assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7251         check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7252
7253         // Broadcast set of revoked txn on A
7254         let hash_128 = connect_blocks(&nodes[0], 40);
7255         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7256         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7257         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7258         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] });
7259         let events = nodes[0].node.get_and_clear_pending_events();
7260         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7261         match events.last().unwrap() {
7262                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7263                 _ => panic!("Unexpected event"),
7264         }
7265         let first;
7266         let feerate_1;
7267         let penalty_txn;
7268         {
7269                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7270                 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7271                 // Verify claim tx are spending revoked HTLC txn
7272
7273                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7274                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7275                 // which are included in the same block (they are broadcasted because we scan the
7276                 // transactions linearly and generate claims as we go, they likely should be removed in the
7277                 // future).
7278                 assert_eq!(node_txn[0].input.len(), 1);
7279                 check_spends!(node_txn[0], revoked_local_txn[0]);
7280                 assert_eq!(node_txn[1].input.len(), 1);
7281                 check_spends!(node_txn[1], revoked_local_txn[0]);
7282                 assert_eq!(node_txn[2].input.len(), 1);
7283                 check_spends!(node_txn[2], revoked_local_txn[0]);
7284
7285                 // Each of the three justice transactions claim a separate (single) output of the three
7286                 // available, which we check here:
7287                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7288                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7289                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7290
7291                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7292                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7293
7294                 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7295                 // output, checked above).
7296                 assert_eq!(node_txn[3].input.len(), 2);
7297                 assert_eq!(node_txn[3].output.len(), 1);
7298                 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7299
7300                 first = node_txn[3].txid();
7301                 // Store both feerates for later comparison
7302                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7303                 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7304                 penalty_txn = vec![node_txn[2].clone()];
7305                 node_txn.clear();
7306         }
7307
7308         // Connect one more block to see if bumped penalty are issued for HTLC txn
7309         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7310         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7311         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7312         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7313
7314         // Few more blocks to confirm penalty txn
7315         connect_blocks(&nodes[0], 4);
7316         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7317         let header_144 = connect_blocks(&nodes[0], 9);
7318         let node_txn = {
7319                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7320                 assert_eq!(node_txn.len(), 1);
7321
7322                 assert_eq!(node_txn[0].input.len(), 2);
7323                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7324                 // Verify bumped tx is different and 25% bump heuristic
7325                 assert_ne!(first, node_txn[0].txid());
7326                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7327                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7328                 assert!(feerate_2 * 100 > feerate_1 * 125);
7329                 let txn = vec![node_txn[0].clone()];
7330                 node_txn.clear();
7331                 txn
7332         };
7333         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7334         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7335         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7336         connect_blocks(&nodes[0], 20);
7337         {
7338                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7339                 // We verify than no new transaction has been broadcast because previously
7340                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7341                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7342                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7343                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7344                 // up bumped justice generation.
7345                 assert_eq!(node_txn.len(), 0);
7346                 node_txn.clear();
7347         }
7348         check_closed_broadcast!(nodes[0], true);
7349         check_added_monitors!(nodes[0], 1);
7350 }
7351
7352 #[test]
7353 fn test_bump_penalty_txn_on_remote_commitment() {
7354         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7355         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7356
7357         // Create 2 HTLCs
7358         // Provide preimage for one
7359         // Check aggregation
7360
7361         let chanmon_cfgs = create_chanmon_cfgs(2);
7362         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7363         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7364         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7365
7366         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7367         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7368         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7369
7370         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7371         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7372         assert_eq!(remote_txn[0].output.len(), 4);
7373         assert_eq!(remote_txn[0].input.len(), 1);
7374         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7375
7376         // Claim a HTLC without revocation (provide B monitor with preimage)
7377         nodes[1].node.claim_funds(payment_preimage);
7378         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7379         mine_transaction(&nodes[1], &remote_txn[0]);
7380         check_added_monitors!(nodes[1], 2);
7381         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7382
7383         // One or more claim tx should have been broadcast, check it
7384         let timeout;
7385         let preimage;
7386         let preimage_bump;
7387         let feerate_timeout;
7388         let feerate_preimage;
7389         {
7390                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7391                 // 3 transactions including:
7392                 //   preimage and timeout sweeps from remote commitment + preimage sweep bump
7393                 assert_eq!(node_txn.len(), 3);
7394                 assert_eq!(node_txn[0].input.len(), 1);
7395                 assert_eq!(node_txn[1].input.len(), 1);
7396                 assert_eq!(node_txn[2].input.len(), 1);
7397                 check_spends!(node_txn[0], remote_txn[0]);
7398                 check_spends!(node_txn[1], remote_txn[0]);
7399                 check_spends!(node_txn[2], remote_txn[0]);
7400
7401                 preimage = node_txn[0].txid();
7402                 let index = node_txn[0].input[0].previous_output.vout;
7403                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7404                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7405
7406                 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7407                         (node_txn[2].clone(), node_txn[1].clone())
7408                 } else {
7409                         (node_txn[1].clone(), node_txn[2].clone())
7410                 };
7411
7412                 preimage_bump = preimage_bump_tx;
7413                 check_spends!(preimage_bump, remote_txn[0]);
7414                 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7415
7416                 timeout = timeout_tx.txid();
7417                 let index = timeout_tx.input[0].previous_output.vout;
7418                 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7419                 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7420
7421                 node_txn.clear();
7422         };
7423         assert_ne!(feerate_timeout, 0);
7424         assert_ne!(feerate_preimage, 0);
7425
7426         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7427         connect_blocks(&nodes[1], 15);
7428         {
7429                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7430                 assert_eq!(node_txn.len(), 1);
7431                 assert_eq!(node_txn[0].input.len(), 1);
7432                 assert_eq!(preimage_bump.input.len(), 1);
7433                 check_spends!(node_txn[0], remote_txn[0]);
7434                 check_spends!(preimage_bump, remote_txn[0]);
7435
7436                 let index = preimage_bump.input[0].previous_output.vout;
7437                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7438                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7439                 assert!(new_feerate * 100 > feerate_timeout * 125);
7440                 assert_ne!(timeout, preimage_bump.txid());
7441
7442                 let index = node_txn[0].input[0].previous_output.vout;
7443                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7444                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7445                 assert!(new_feerate * 100 > feerate_preimage * 125);
7446                 assert_ne!(preimage, node_txn[0].txid());
7447
7448                 node_txn.clear();
7449         }
7450
7451         nodes[1].node.get_and_clear_pending_events();
7452         nodes[1].node.get_and_clear_pending_msg_events();
7453 }
7454
7455 #[test]
7456 fn test_counterparty_raa_skip_no_crash() {
7457         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7458         // commitment transaction, we would have happily carried on and provided them the next
7459         // commitment transaction based on one RAA forward. This would probably eventually have led to
7460         // channel closure, but it would not have resulted in funds loss. Still, our
7461         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7462         // check simply that the channel is closed in response to such an RAA, but don't check whether
7463         // we decide to punish our counterparty for revoking their funds (as we don't currently
7464         // implement that).
7465         let chanmon_cfgs = create_chanmon_cfgs(2);
7466         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7467         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7468         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7469         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7470
7471         let per_commitment_secret;
7472         let next_per_commitment_point;
7473         {
7474                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7475                 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7476                 let keys = guard.channel_by_id.get_mut(&channel_id).unwrap().get_signer();
7477
7478                 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7479
7480                 // Make signer believe we got a counterparty signature, so that it allows the revocation
7481                 keys.get_enforcement_state().last_holder_commitment -= 1;
7482                 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7483
7484                 // Must revoke without gaps
7485                 keys.get_enforcement_state().last_holder_commitment -= 1;
7486                 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7487
7488                 keys.get_enforcement_state().last_holder_commitment -= 1;
7489                 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7490                         &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7491         }
7492
7493         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7494                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7495         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7496         check_added_monitors!(nodes[1], 1);
7497         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7498 }
7499
7500 #[test]
7501 fn test_bump_txn_sanitize_tracking_maps() {
7502         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7503         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7504
7505         let chanmon_cfgs = create_chanmon_cfgs(2);
7506         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7507         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7508         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7509
7510         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7511         // Lock HTLC in both directions
7512         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7513         let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7514
7515         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7516         assert_eq!(revoked_local_txn[0].input.len(), 1);
7517         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7518
7519         // Revoke local commitment tx
7520         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7521
7522         // Broadcast set of revoked txn on A
7523         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7524         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7525         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7526
7527         mine_transaction(&nodes[0], &revoked_local_txn[0]);
7528         check_closed_broadcast!(nodes[0], true);
7529         check_added_monitors!(nodes[0], 1);
7530         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7531         let penalty_txn = {
7532                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7533                 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7534                 check_spends!(node_txn[0], revoked_local_txn[0]);
7535                 check_spends!(node_txn[1], revoked_local_txn[0]);
7536                 check_spends!(node_txn[2], revoked_local_txn[0]);
7537                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7538                 node_txn.clear();
7539                 penalty_txn
7540         };
7541         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7542         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7543         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7544         {
7545                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7546                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7547                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7548         }
7549 }
7550
7551 #[test]
7552 fn test_pending_claimed_htlc_no_balance_underflow() {
7553         // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
7554         // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
7555         let chanmon_cfgs = create_chanmon_cfgs(2);
7556         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7557         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7558         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7559         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
7560
7561         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
7562         nodes[1].node.claim_funds(payment_preimage);
7563         expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
7564         check_added_monitors!(nodes[1], 1);
7565         let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7566
7567         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
7568         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
7569         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
7570         check_added_monitors!(nodes[0], 1);
7571         let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7572
7573         // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
7574         // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
7575         // can get our balance.
7576
7577         // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
7578         // the public key of the only hop. This works around ChannelDetails not showing the
7579         // almost-claimed HTLC as available balance.
7580         let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
7581         route.payment_params = None; // This is all wrong, but unnecessary
7582         route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
7583         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
7584         nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
7585
7586         assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
7587 }
7588
7589 #[test]
7590 fn test_channel_conf_timeout() {
7591         // Tests that, for inbound channels, we give up on them if the funding transaction does not
7592         // confirm within 2016 blocks, as recommended by BOLT 2.
7593         let chanmon_cfgs = create_chanmon_cfgs(2);
7594         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7595         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7596         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7597
7598         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7599
7600         // The outbound node should wait forever for confirmation:
7601         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7602         // copied here instead of directly referencing the constant.
7603         connect_blocks(&nodes[0], 2016);
7604         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7605
7606         // The inbound node should fail the channel after exactly 2016 blocks
7607         connect_blocks(&nodes[1], 2015);
7608         check_added_monitors!(nodes[1], 0);
7609         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7610
7611         connect_blocks(&nodes[1], 1);
7612         check_added_monitors!(nodes[1], 1);
7613         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
7614         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7615         assert_eq!(close_ev.len(), 1);
7616         match close_ev[0] {
7617                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7618                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7619                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7620                 },
7621                 _ => panic!("Unexpected event"),
7622         }
7623 }
7624
7625 #[test]
7626 fn test_override_channel_config() {
7627         let chanmon_cfgs = create_chanmon_cfgs(2);
7628         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7629         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7630         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7631
7632         // Node0 initiates a channel to node1 using the override config.
7633         let mut override_config = UserConfig::default();
7634         override_config.channel_handshake_config.our_to_self_delay = 200;
7635
7636         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7637
7638         // Assert the channel created by node0 is using the override config.
7639         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7640         assert_eq!(res.channel_flags, 0);
7641         assert_eq!(res.to_self_delay, 200);
7642 }
7643
7644 #[test]
7645 fn test_override_0msat_htlc_minimum() {
7646         let mut zero_config = UserConfig::default();
7647         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7648         let chanmon_cfgs = create_chanmon_cfgs(2);
7649         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7650         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7651         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7652
7653         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7654         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7655         assert_eq!(res.htlc_minimum_msat, 1);
7656
7657         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7658         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7659         assert_eq!(res.htlc_minimum_msat, 1);
7660 }
7661
7662 #[test]
7663 fn test_channel_update_has_correct_htlc_maximum_msat() {
7664         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7665         // Bolt 7 specifies that if present `htlc_maximum_msat`:
7666         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7667         // 90% of the `channel_value`.
7668         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7669
7670         let mut config_30_percent = UserConfig::default();
7671         config_30_percent.channel_handshake_config.announced_channel = true;
7672         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7673         let mut config_50_percent = UserConfig::default();
7674         config_50_percent.channel_handshake_config.announced_channel = true;
7675         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7676         let mut config_95_percent = UserConfig::default();
7677         config_95_percent.channel_handshake_config.announced_channel = true;
7678         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7679         let mut config_100_percent = UserConfig::default();
7680         config_100_percent.channel_handshake_config.announced_channel = true;
7681         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7682
7683         let chanmon_cfgs = create_chanmon_cfgs(4);
7684         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7685         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)]);
7686         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7687
7688         let channel_value_satoshis = 100000;
7689         let channel_value_msat = channel_value_satoshis * 1000;
7690         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7691         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7692         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7693
7694         let (node_0_chan_update, node_1_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7695         let (node_2_chan_update, node_3_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7696
7697         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7698         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7699         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7700         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7701         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7702         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7703
7704         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7705         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7706         // `channel_value`.
7707         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7708         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7709         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7710         // `channel_value`.
7711         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7712 }
7713
7714 #[test]
7715 fn test_manually_accept_inbound_channel_request() {
7716         let mut manually_accept_conf = UserConfig::default();
7717         manually_accept_conf.manually_accept_inbound_channels = true;
7718         let chanmon_cfgs = create_chanmon_cfgs(2);
7719         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7720         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7721         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7722
7723         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7724         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7725
7726         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7727
7728         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7729         // accepting the inbound channel request.
7730         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7731
7732         let events = nodes[1].node.get_and_clear_pending_events();
7733         match events[0] {
7734                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7735                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7736                 }
7737                 _ => panic!("Unexpected event"),
7738         }
7739
7740         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7741         assert_eq!(accept_msg_ev.len(), 1);
7742
7743         match accept_msg_ev[0] {
7744                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7745                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7746                 }
7747                 _ => panic!("Unexpected event"),
7748         }
7749
7750         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7751
7752         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7753         assert_eq!(close_msg_ev.len(), 1);
7754
7755         let events = nodes[1].node.get_and_clear_pending_events();
7756         match events[0] {
7757                 Event::ChannelClosed { user_channel_id, .. } => {
7758                         assert_eq!(user_channel_id, 23);
7759                 }
7760                 _ => panic!("Unexpected event"),
7761         }
7762 }
7763
7764 #[test]
7765 fn test_manually_reject_inbound_channel_request() {
7766         let mut manually_accept_conf = UserConfig::default();
7767         manually_accept_conf.manually_accept_inbound_channels = true;
7768         let chanmon_cfgs = create_chanmon_cfgs(2);
7769         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7770         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7771         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7772
7773         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7774         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7775
7776         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7777
7778         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7779         // rejecting the inbound channel request.
7780         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7781
7782         let events = nodes[1].node.get_and_clear_pending_events();
7783         match events[0] {
7784                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7785                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7786                 }
7787                 _ => panic!("Unexpected event"),
7788         }
7789
7790         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7791         assert_eq!(close_msg_ev.len(), 1);
7792
7793         match close_msg_ev[0] {
7794                 MessageSendEvent::HandleError { ref node_id, .. } => {
7795                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7796                 }
7797                 _ => panic!("Unexpected event"),
7798         }
7799         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
7800 }
7801
7802 #[test]
7803 fn test_reject_funding_before_inbound_channel_accepted() {
7804         // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
7805         // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
7806         // the node operator before the counterparty sends a `FundingCreated` message. If a
7807         // `FundingCreated` message is received before the channel is accepted, it should be rejected
7808         // and the channel should be closed.
7809         let mut manually_accept_conf = UserConfig::default();
7810         manually_accept_conf.manually_accept_inbound_channels = true;
7811         let chanmon_cfgs = create_chanmon_cfgs(2);
7812         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7813         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7814         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7815
7816         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7817         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7818         let temp_channel_id = res.temporary_channel_id;
7819
7820         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7821
7822         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
7823         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7824
7825         // Clear the `Event::OpenChannelRequest` event without responding to the request.
7826         nodes[1].node.get_and_clear_pending_events();
7827
7828         // Get the `AcceptChannel` message of `nodes[1]` without calling
7829         // `ChannelManager::accept_inbound_channel`, which generates a
7830         // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
7831         // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
7832         // succeed when `nodes[0]` is passed to it.
7833         let accept_chan_msg = {
7834                 let mut node_1_per_peer_lock;
7835                 let mut node_1_peer_state_lock;
7836                 let channel =  get_channel_ref!(&nodes[1], nodes[0], node_1_per_peer_lock, node_1_peer_state_lock, temp_channel_id);
7837                 channel.get_accept_channel_message()
7838         };
7839         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
7840
7841         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
7842
7843         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
7844         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
7845
7846         // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
7847         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
7848
7849         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7850         assert_eq!(close_msg_ev.len(), 1);
7851
7852         let expected_err = "FundingCreated message received before the channel was accepted";
7853         match close_msg_ev[0] {
7854                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
7855                         assert_eq!(msg.channel_id, temp_channel_id);
7856                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7857                         assert_eq!(msg.data, expected_err);
7858                 }
7859                 _ => panic!("Unexpected event"),
7860         }
7861
7862         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
7863 }
7864
7865 #[test]
7866 fn test_can_not_accept_inbound_channel_twice() {
7867         let mut manually_accept_conf = UserConfig::default();
7868         manually_accept_conf.manually_accept_inbound_channels = true;
7869         let chanmon_cfgs = create_chanmon_cfgs(2);
7870         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7871         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7872         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7873
7874         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7875         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7876
7877         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7878
7879         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7880         // accepting the inbound channel request.
7881         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7882
7883         let events = nodes[1].node.get_and_clear_pending_events();
7884         match events[0] {
7885                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7886                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7887                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7888                         match api_res {
7889                                 Err(APIError::APIMisuseError { err }) => {
7890                                         assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
7891                                 },
7892                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7893                                 Err(_) => panic!("Unexpected Error"),
7894                         }
7895                 }
7896                 _ => panic!("Unexpected event"),
7897         }
7898
7899         // Ensure that the channel wasn't closed after attempting to accept it twice.
7900         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7901         assert_eq!(accept_msg_ev.len(), 1);
7902
7903         match accept_msg_ev[0] {
7904                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7905                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7906                 }
7907                 _ => panic!("Unexpected event"),
7908         }
7909 }
7910
7911 #[test]
7912 fn test_can_not_accept_unknown_inbound_channel() {
7913         let chanmon_cfg = create_chanmon_cfgs(2);
7914         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
7915         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
7916         let nodes = create_network(2, &node_cfg, &node_chanmgr);
7917
7918         let unknown_channel_id = [0; 32];
7919         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
7920         match api_res {
7921                 Err(APIError::ChannelUnavailable { err }) => {
7922                         assert_eq!(err, format!("Channel with id {} not found for the passed counterparty node_id {}", log_bytes!(unknown_channel_id), nodes[1].node.get_our_node_id()));
7923                 },
7924                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
7925                 Err(_) => panic!("Unexpected Error"),
7926         }
7927 }
7928
7929 #[test]
7930 fn test_simple_mpp() {
7931         // Simple test of sending a multi-path payment.
7932         let chanmon_cfgs = create_chanmon_cfgs(4);
7933         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7934         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
7935         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7936
7937         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
7938         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
7939         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
7940         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
7941
7942         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
7943         let path = route.paths[0].clone();
7944         route.paths.push(path);
7945         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
7946         route.paths[0][0].short_channel_id = chan_1_id;
7947         route.paths[0][1].short_channel_id = chan_3_id;
7948         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
7949         route.paths[1][0].short_channel_id = chan_2_id;
7950         route.paths[1][1].short_channel_id = chan_4_id;
7951         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
7952         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
7953 }
7954
7955 #[test]
7956 fn test_preimage_storage() {
7957         // Simple test of payment preimage storage allowing no client-side storage to claim payments
7958         let chanmon_cfgs = create_chanmon_cfgs(2);
7959         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7960         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7961         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7962
7963         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
7964
7965         {
7966                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
7967                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
7968                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
7969                 check_added_monitors!(nodes[0], 1);
7970                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7971                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7972                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7973                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7974         }
7975         // Note that after leaving the above scope we have no knowledge of any arguments or return
7976         // values from previous calls.
7977         expect_pending_htlcs_forwardable!(nodes[1]);
7978         let events = nodes[1].node.get_and_clear_pending_events();
7979         assert_eq!(events.len(), 1);
7980         match events[0] {
7981                 Event::PaymentClaimable { ref purpose, .. } => {
7982                         match &purpose {
7983                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
7984                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
7985                                 },
7986                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
7987                         }
7988                 },
7989                 _ => panic!("Unexpected event"),
7990         }
7991 }
7992
7993 #[test]
7994 #[allow(deprecated)]
7995 fn test_secret_timeout() {
7996         // Simple test of payment secret storage time outs. After
7997         // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
7998         let chanmon_cfgs = create_chanmon_cfgs(2);
7999         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8000         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8001         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8002
8003         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8004
8005         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8006
8007         // We should fail to register the same payment hash twice, at least until we've connected a
8008         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8009         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8010                 assert_eq!(err, "Duplicate payment hash");
8011         } else { panic!(); }
8012         let mut block = {
8013                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8014                 Block {
8015                         header: BlockHeader {
8016                                 version: 0x2000000,
8017                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8018                                 merkle_root: TxMerkleNode::all_zeros(),
8019                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8020                         txdata: vec![],
8021                 }
8022         };
8023         connect_block(&nodes[1], &block);
8024         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8025                 assert_eq!(err, "Duplicate payment hash");
8026         } else { panic!(); }
8027
8028         // If we then connect the second block, we should be able to register the same payment hash
8029         // again (this time getting a new payment secret).
8030         block.header.prev_blockhash = block.header.block_hash();
8031         block.header.time += 1;
8032         connect_block(&nodes[1], &block);
8033         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8034         assert_ne!(payment_secret_1, our_payment_secret);
8035
8036         {
8037                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8038                 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret), PaymentId(payment_hash.0)).unwrap();
8039                 check_added_monitors!(nodes[0], 1);
8040                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8041                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8042                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8043                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8044         }
8045         // Note that after leaving the above scope we have no knowledge of any arguments or return
8046         // values from previous calls.
8047         expect_pending_htlcs_forwardable!(nodes[1]);
8048         let events = nodes[1].node.get_and_clear_pending_events();
8049         assert_eq!(events.len(), 1);
8050         match events[0] {
8051                 Event::PaymentClaimable { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8052                         assert!(payment_preimage.is_none());
8053                         assert_eq!(payment_secret, our_payment_secret);
8054                         // We don't actually have the payment preimage with which to claim this payment!
8055                 },
8056                 _ => panic!("Unexpected event"),
8057         }
8058 }
8059
8060 #[test]
8061 fn test_bad_secret_hash() {
8062         // Simple test of unregistered payment hash/invalid payment secret handling
8063         let chanmon_cfgs = create_chanmon_cfgs(2);
8064         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8065         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8066         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8067
8068         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8069
8070         let random_payment_hash = PaymentHash([42; 32]);
8071         let random_payment_secret = PaymentSecret([43; 32]);
8072         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8073         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8074
8075         // All the below cases should end up being handled exactly identically, so we macro the
8076         // resulting events.
8077         macro_rules! handle_unknown_invalid_payment_data {
8078                 ($payment_hash: expr) => {
8079                         check_added_monitors!(nodes[0], 1);
8080                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8081                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8082                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8083                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8084
8085                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8086                         // again to process the pending backwards-failure of the HTLC
8087                         expect_pending_htlcs_forwardable!(nodes[1]);
8088                         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8089                         check_added_monitors!(nodes[1], 1);
8090
8091                         // We should fail the payment back
8092                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8093                         match events.pop().unwrap() {
8094                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8095                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8096                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8097                                 },
8098                                 _ => panic!("Unexpected event"),
8099                         }
8100                 }
8101         }
8102
8103         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8104         // Error data is the HTLC value (100,000) and current block height
8105         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8106
8107         // Send a payment with the right payment hash but the wrong payment secret
8108         nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8109         handle_unknown_invalid_payment_data!(our_payment_hash);
8110         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8111
8112         // Send a payment with a random payment hash, but the right payment secret
8113         nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8114         handle_unknown_invalid_payment_data!(random_payment_hash);
8115         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8116
8117         // Send a payment with a random payment hash and random payment secret
8118         nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8119         handle_unknown_invalid_payment_data!(random_payment_hash);
8120         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8121 }
8122
8123 #[test]
8124 fn test_update_err_monitor_lockdown() {
8125         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8126         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8127         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8128         // error.
8129         //
8130         // This scenario may happen in a watchtower setup, where watchtower process a block height
8131         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8132         // commitment at same time.
8133
8134         let chanmon_cfgs = create_chanmon_cfgs(2);
8135         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8136         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8137         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8138
8139         // Create some initial channel
8140         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8141         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8142
8143         // Rebalance the network to generate htlc in the two directions
8144         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8145
8146         // Route a HTLC from node 0 to node 1 (but don't settle)
8147         let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8148
8149         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8150         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8151         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8152         let persister = test_utils::TestPersister::new();
8153         let watchtower = {
8154                 let new_monitor = {
8155                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8156                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8157                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8158                         assert!(new_monitor == *monitor);
8159                         new_monitor
8160                 };
8161                 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);
8162                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8163                 watchtower
8164         };
8165         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8166         let block = Block { header, txdata: vec![] };
8167         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8168         // transaction lock time requirements here.
8169         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8170         watchtower.chain_monitor.block_connected(&block, 200);
8171
8172         // Try to update ChannelMonitor
8173         nodes[1].node.claim_funds(preimage);
8174         check_added_monitors!(nodes[1], 1);
8175         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8176
8177         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8178         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8179         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8180         {
8181                 let mut node_0_per_peer_lock;
8182                 let mut node_0_peer_state_lock;
8183                 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8184                 if let Ok(update) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8185                         assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8186                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8187                 } else { assert!(false); }
8188         }
8189         // Our local monitor is in-sync and hasn't processed yet timeout
8190         check_added_monitors!(nodes[0], 1);
8191         let events = nodes[0].node.get_and_clear_pending_events();
8192         assert_eq!(events.len(), 1);
8193 }
8194
8195 #[test]
8196 fn test_concurrent_monitor_claim() {
8197         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8198         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8199         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8200         // state N+1 confirms. Alice claims output from state N+1.
8201
8202         let chanmon_cfgs = create_chanmon_cfgs(2);
8203         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8204         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8205         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8206
8207         // Create some initial channel
8208         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8209         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8210
8211         // Rebalance the network to generate htlc in the two directions
8212         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8213
8214         // Route a HTLC from node 0 to node 1 (but don't settle)
8215         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8216
8217         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8218         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8219         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8220         let persister = test_utils::TestPersister::new();
8221         let watchtower_alice = {
8222                 let new_monitor = {
8223                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8224                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8225                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8226                         assert!(new_monitor == *monitor);
8227                         new_monitor
8228                 };
8229                 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);
8230                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8231                 watchtower
8232         };
8233         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8234         let block = Block { header, txdata: vec![] };
8235         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8236         // transaction lock time requirements here.
8237         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));
8238         watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8239
8240         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8241         {
8242                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8243                 assert_eq!(txn.len(), 2);
8244                 txn.clear();
8245         }
8246
8247         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8248         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8249         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8250         let persister = test_utils::TestPersister::new();
8251         let watchtower_bob = {
8252                 let new_monitor = {
8253                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8254                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8255                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8256                         assert!(new_monitor == *monitor);
8257                         new_monitor
8258                 };
8259                 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);
8260                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8261                 watchtower
8262         };
8263         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8264         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8265
8266         // Route another payment to generate another update with still previous HTLC pending
8267         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8268         {
8269                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
8270         }
8271         check_added_monitors!(nodes[1], 1);
8272
8273         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8274         assert_eq!(updates.update_add_htlcs.len(), 1);
8275         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8276         {
8277                 let mut node_0_per_peer_lock;
8278                 let mut node_0_peer_state_lock;
8279                 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8280                 if let Ok(update) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8281                         // Watchtower Alice should already have seen the block and reject the update
8282                         assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8283                         assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8284                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8285                 } else { assert!(false); }
8286         }
8287         // Our local monitor is in-sync and hasn't processed yet timeout
8288         check_added_monitors!(nodes[0], 1);
8289
8290         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8291         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8292         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8293
8294         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8295         let bob_state_y;
8296         {
8297                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8298                 assert_eq!(txn.len(), 2);
8299                 bob_state_y = txn[0].clone();
8300                 txn.clear();
8301         };
8302
8303         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8304         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8305         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);
8306         {
8307                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8308                 assert_eq!(htlc_txn.len(), 1);
8309                 check_spends!(htlc_txn[0], bob_state_y);
8310         }
8311 }
8312
8313 #[test]
8314 fn test_pre_lockin_no_chan_closed_update() {
8315         // Test that if a peer closes a channel in response to a funding_created message we don't
8316         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8317         // message).
8318         //
8319         // Doing so would imply a channel monitor update before the initial channel monitor
8320         // registration, violating our API guarantees.
8321         //
8322         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8323         // then opening a second channel with the same funding output as the first (which is not
8324         // rejected because the first channel does not exist in the ChannelManager) and closing it
8325         // before receiving funding_signed.
8326         let chanmon_cfgs = create_chanmon_cfgs(2);
8327         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8328         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8329         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8330
8331         // Create an initial channel
8332         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8333         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8334         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8335         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8336         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8337
8338         // Move the first channel through the funding flow...
8339         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8340
8341         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8342         check_added_monitors!(nodes[0], 0);
8343
8344         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8345         let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8346         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8347         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8348         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true);
8349 }
8350
8351 #[test]
8352 fn test_htlc_no_detection() {
8353         // This test is a mutation to underscore the detection logic bug we had
8354         // before #653. HTLC value routed is above the remaining balance, thus
8355         // inverting HTLC and `to_remote` output. HTLC will come second and
8356         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8357         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8358         // outputs order detection for correct spending children filtring.
8359
8360         let chanmon_cfgs = create_chanmon_cfgs(2);
8361         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8362         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8363         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8364
8365         // Create some initial channels
8366         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8367
8368         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8369         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8370         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8371         assert_eq!(local_txn[0].input.len(), 1);
8372         assert_eq!(local_txn[0].output.len(), 3);
8373         check_spends!(local_txn[0], chan_1.3);
8374
8375         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8376         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8377         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8378         // We deliberately connect the local tx twice as this should provoke a failure calling
8379         // this test before #653 fix.
8380         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);
8381         check_closed_broadcast!(nodes[0], true);
8382         check_added_monitors!(nodes[0], 1);
8383         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8384         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8385
8386         let htlc_timeout = {
8387                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8388                 assert_eq!(node_txn.len(), 1);
8389                 assert_eq!(node_txn[0].input.len(), 1);
8390                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8391                 check_spends!(node_txn[0], local_txn[0]);
8392                 node_txn[0].clone()
8393         };
8394
8395         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8396         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8397         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8398         expect_payment_failed!(nodes[0], our_payment_hash, false);
8399 }
8400
8401 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8402         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8403         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8404         // Carol, Alice would be the upstream node, and Carol the downstream.)
8405         //
8406         // Steps of the test:
8407         // 1) Alice sends a HTLC to Carol through Bob.
8408         // 2) Carol doesn't settle the HTLC.
8409         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8410         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8411         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8412         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8413         // 5) Carol release the preimage to Bob off-chain.
8414         // 6) Bob claims the offered output on the broadcasted commitment.
8415         let chanmon_cfgs = create_chanmon_cfgs(3);
8416         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8417         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8418         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8419
8420         // Create some initial channels
8421         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8422         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8423
8424         // Steps (1) and (2):
8425         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8426         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8427
8428         // Check that Alice's commitment transaction now contains an output for this HTLC.
8429         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8430         check_spends!(alice_txn[0], chan_ab.3);
8431         assert_eq!(alice_txn[0].output.len(), 2);
8432         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8433         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8434         assert_eq!(alice_txn.len(), 2);
8435
8436         // Steps (3) and (4):
8437         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8438         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8439         let mut force_closing_node = 0; // Alice force-closes
8440         let mut counterparty_node = 1; // Bob if Alice force-closes
8441
8442         // Bob force-closes
8443         if !broadcast_alice {
8444                 force_closing_node = 1;
8445                 counterparty_node = 0;
8446         }
8447         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8448         check_closed_broadcast!(nodes[force_closing_node], true);
8449         check_added_monitors!(nodes[force_closing_node], 1);
8450         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8451         if go_onchain_before_fulfill {
8452                 let txn_to_broadcast = match broadcast_alice {
8453                         true => alice_txn.clone(),
8454                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8455                 };
8456                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8457                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8458                 if broadcast_alice {
8459                         check_closed_broadcast!(nodes[1], true);
8460                         check_added_monitors!(nodes[1], 1);
8461                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8462                 }
8463         }
8464
8465         // Step (5):
8466         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8467         // process of removing the HTLC from their commitment transactions.
8468         nodes[2].node.claim_funds(payment_preimage);
8469         check_added_monitors!(nodes[2], 1);
8470         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8471
8472         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8473         assert!(carol_updates.update_add_htlcs.is_empty());
8474         assert!(carol_updates.update_fail_htlcs.is_empty());
8475         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8476         assert!(carol_updates.update_fee.is_none());
8477         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8478
8479         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8480         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8481         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8482         if !go_onchain_before_fulfill && broadcast_alice {
8483                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8484                 assert_eq!(events.len(), 1);
8485                 match events[0] {
8486                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8487                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8488                         },
8489                         _ => panic!("Unexpected event"),
8490                 };
8491         }
8492         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8493         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8494         // Carol<->Bob's updated commitment transaction info.
8495         check_added_monitors!(nodes[1], 2);
8496
8497         let events = nodes[1].node.get_and_clear_pending_msg_events();
8498         assert_eq!(events.len(), 2);
8499         let bob_revocation = match events[0] {
8500                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8501                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8502                         (*msg).clone()
8503                 },
8504                 _ => panic!("Unexpected event"),
8505         };
8506         let bob_updates = match events[1] {
8507                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8508                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8509                         (*updates).clone()
8510                 },
8511                 _ => panic!("Unexpected event"),
8512         };
8513
8514         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8515         check_added_monitors!(nodes[2], 1);
8516         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8517         check_added_monitors!(nodes[2], 1);
8518
8519         let events = nodes[2].node.get_and_clear_pending_msg_events();
8520         assert_eq!(events.len(), 1);
8521         let carol_revocation = match events[0] {
8522                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8523                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8524                         (*msg).clone()
8525                 },
8526                 _ => panic!("Unexpected event"),
8527         };
8528         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8529         check_added_monitors!(nodes[1], 1);
8530
8531         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8532         // here's where we put said channel's commitment tx on-chain.
8533         let mut txn_to_broadcast = alice_txn.clone();
8534         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8535         if !go_onchain_before_fulfill {
8536                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8537                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8538                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8539                 if broadcast_alice {
8540                         check_closed_broadcast!(nodes[1], true);
8541                         check_added_monitors!(nodes[1], 1);
8542                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8543                 }
8544                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8545                 if broadcast_alice {
8546                         assert_eq!(bob_txn.len(), 1);
8547                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8548                 } else {
8549                         assert_eq!(bob_txn.len(), 2);
8550                         check_spends!(bob_txn[0], chan_ab.3);
8551                 }
8552         }
8553
8554         // Step (6):
8555         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8556         // broadcasted commitment transaction.
8557         {
8558                 let script_weight = match broadcast_alice {
8559                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8560                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8561                 };
8562                 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8563                 // Bob force-closed and broadcasts the commitment transaction along with a
8564                 // HTLC-output-claiming transaction.
8565                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8566                 if broadcast_alice {
8567                         assert_eq!(bob_txn.len(), 1);
8568                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8569                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8570                 } else {
8571                         assert_eq!(bob_txn.len(), 2);
8572                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8573                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8574                 }
8575         }
8576 }
8577
8578 #[test]
8579 fn test_onchain_htlc_settlement_after_close() {
8580         do_test_onchain_htlc_settlement_after_close(true, true);
8581         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8582         do_test_onchain_htlc_settlement_after_close(true, false);
8583         do_test_onchain_htlc_settlement_after_close(false, false);
8584 }
8585
8586 #[test]
8587 fn test_duplicate_temporary_channel_id_from_different_peers() {
8588         // Tests that we can accept two different `OpenChannel` requests with the same
8589         // `temporary_channel_id`, as long as they are from different peers.
8590         let chanmon_cfgs = create_chanmon_cfgs(3);
8591         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8592         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8593         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8594
8595         // Create an first channel channel
8596         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8597         let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8598
8599         // Create an second channel
8600         nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8601         let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8602
8603         // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8604         // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8605         open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8606
8607         // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8608         // `temporary_channel_id` as they are from different peers.
8609         nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8610         {
8611                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8612                 assert_eq!(events.len(), 1);
8613                 match &events[0] {
8614                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8615                                 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8616                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8617                         },
8618                         _ => panic!("Unexpected event"),
8619                 }
8620         }
8621
8622         nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8623         {
8624                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8625                 assert_eq!(events.len(), 1);
8626                 match &events[0] {
8627                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8628                                 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8629                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8630                         },
8631                         _ => panic!("Unexpected event"),
8632                 }
8633         }
8634 }
8635
8636 #[test]
8637 fn test_duplicate_chan_id() {
8638         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8639         // already open we reject it and keep the old channel.
8640         //
8641         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8642         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8643         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8644         // updating logic for the existing channel.
8645         let chanmon_cfgs = create_chanmon_cfgs(2);
8646         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8647         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8648         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8649
8650         // Create an initial channel
8651         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8652         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8653         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8654         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
8655
8656         // Try to create a second channel with the same temporary_channel_id as the first and check
8657         // that it is rejected.
8658         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8659         {
8660                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8661                 assert_eq!(events.len(), 1);
8662                 match events[0] {
8663                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8664                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8665                                 // first (valid) and second (invalid) channels are closed, given they both have
8666                                 // the same non-temporary channel_id. However, currently we do not, so we just
8667                                 // move forward with it.
8668                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8669                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8670                         },
8671                         _ => panic!("Unexpected event"),
8672                 }
8673         }
8674
8675         // Move the first channel through the funding flow...
8676         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8677
8678         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8679         check_added_monitors!(nodes[0], 0);
8680
8681         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8682         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8683         {
8684                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8685                 assert_eq!(added_monitors.len(), 1);
8686                 assert_eq!(added_monitors[0].0, funding_output);
8687                 added_monitors.clear();
8688         }
8689         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8690
8691         let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8692         let channel_id = funding_outpoint.to_channel_id();
8693
8694         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8695         // temporary one).
8696
8697         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8698         // Technically this is allowed by the spec, but we don't support it and there's little reason
8699         // to. Still, it shouldn't cause any other issues.
8700         open_chan_msg.temporary_channel_id = channel_id;
8701         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8702         {
8703                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8704                 assert_eq!(events.len(), 1);
8705                 match events[0] {
8706                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8707                                 // Technically, at this point, nodes[1] would be justified in thinking both
8708                                 // channels are closed, but currently we do not, so we just move forward with it.
8709                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8710                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8711                         },
8712                         _ => panic!("Unexpected event"),
8713                 }
8714         }
8715
8716         // Now try to create a second channel which has a duplicate funding output.
8717         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8718         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8719         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
8720         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
8721         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8722
8723         let funding_created = {
8724                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8725                 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
8726                 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
8727                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8728                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8729                 // channelmanager in a possibly nonsense state instead).
8730                 let mut as_chan = a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8731                 let logger = test_utils::TestLogger::new();
8732                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8733         };
8734         check_added_monitors!(nodes[0], 0);
8735         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8736         // At this point we'll look up if the channel_id is present and immediately fail the channel
8737         // without trying to persist the `ChannelMonitor`.
8738         check_added_monitors!(nodes[1], 0);
8739
8740         // ...still, nodes[1] will reject the duplicate channel.
8741         {
8742                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8743                 assert_eq!(events.len(), 1);
8744                 match events[0] {
8745                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8746                                 // Technically, at this point, nodes[1] would be justified in thinking both
8747                                 // channels are closed, but currently we do not, so we just move forward with it.
8748                                 assert_eq!(msg.channel_id, channel_id);
8749                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8750                         },
8751                         _ => panic!("Unexpected event"),
8752                 }
8753         }
8754
8755         // finally, finish creating the original channel and send a payment over it to make sure
8756         // everything is functional.
8757         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8758         {
8759                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8760                 assert_eq!(added_monitors.len(), 1);
8761                 assert_eq!(added_monitors[0].0, funding_output);
8762                 added_monitors.clear();
8763         }
8764
8765         let events_4 = nodes[0].node.get_and_clear_pending_events();
8766         assert_eq!(events_4.len(), 0);
8767         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8768         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8769
8770         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8771         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
8772         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8773
8774         send_payment(&nodes[0], &[&nodes[1]], 8000000);
8775 }
8776
8777 #[test]
8778 fn test_error_chans_closed() {
8779         // Test that we properly handle error messages, closing appropriate channels.
8780         //
8781         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8782         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8783         // we can test various edge cases around it to ensure we don't regress.
8784         let chanmon_cfgs = create_chanmon_cfgs(3);
8785         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8786         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8787         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8788
8789         // Create some initial channels
8790         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8791         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8792         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
8793
8794         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8795         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8796         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8797
8798         // Closing a channel from a different peer has no effect
8799         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8800         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8801
8802         // Closing one channel doesn't impact others
8803         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8804         check_added_monitors!(nodes[0], 1);
8805         check_closed_broadcast!(nodes[0], false);
8806         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
8807         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8808         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8809         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);
8810         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);
8811
8812         // A null channel ID should close all channels
8813         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8814         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8815         check_added_monitors!(nodes[0], 2);
8816         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
8817         let events = nodes[0].node.get_and_clear_pending_msg_events();
8818         assert_eq!(events.len(), 2);
8819         match events[0] {
8820                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8821                         assert_eq!(msg.contents.flags & 2, 2);
8822                 },
8823                 _ => panic!("Unexpected event"),
8824         }
8825         match events[1] {
8826                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8827                         assert_eq!(msg.contents.flags & 2, 2);
8828                 },
8829                 _ => panic!("Unexpected event"),
8830         }
8831         // Note that at this point users of a standard PeerHandler will end up calling
8832         // peer_disconnected.
8833         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8834         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8835
8836         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
8837         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8838         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8839 }
8840
8841 #[test]
8842 fn test_invalid_funding_tx() {
8843         // Test that we properly handle invalid funding transactions sent to us from a peer.
8844         //
8845         // Previously, all other major lightning implementations had failed to properly sanitize
8846         // funding transactions from their counterparties, leading to a multi-implementation critical
8847         // security vulnerability (though we always sanitized properly, we've previously had
8848         // un-released crashes in the sanitization process).
8849         //
8850         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
8851         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
8852         // gave up on it. We test this here by generating such a transaction.
8853         let chanmon_cfgs = create_chanmon_cfgs(2);
8854         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8855         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8856         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8857
8858         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
8859         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
8860         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
8861
8862         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
8863
8864         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
8865         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
8866         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
8867         // its length.
8868         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
8869         let wit_program_script: Script = wit_program.into();
8870         for output in tx.output.iter_mut() {
8871                 // Make the confirmed funding transaction have a bogus script_pubkey
8872                 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
8873         }
8874
8875         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
8876         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()));
8877         check_added_monitors!(nodes[1], 1);
8878
8879         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()));
8880         check_added_monitors!(nodes[0], 1);
8881
8882         let events_1 = nodes[0].node.get_and_clear_pending_events();
8883         assert_eq!(events_1.len(), 0);
8884
8885         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8886         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8887         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
8888
8889         let expected_err = "funding tx had wrong script/value or output index";
8890         confirm_transaction_at(&nodes[1], &tx, 1);
8891         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8892         check_added_monitors!(nodes[1], 1);
8893         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
8894         assert_eq!(events_2.len(), 1);
8895         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
8896                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8897                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
8898                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
8899                 } else { panic!(); }
8900         } else { panic!(); }
8901         assert_eq!(nodes[1].node.list_channels().len(), 0);
8902
8903         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
8904         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
8905         // as its not 32 bytes long.
8906         let mut spend_tx = Transaction {
8907                 version: 2i32, lock_time: PackedLockTime::ZERO,
8908                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
8909                         previous_output: BitcoinOutPoint {
8910                                 txid: tx.txid(),
8911                                 vout: idx as u32,
8912                         },
8913                         script_sig: Script::new(),
8914                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
8915                         witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
8916                 }).collect(),
8917                 output: vec![TxOut {
8918                         value: 1000,
8919                         script_pubkey: Script::new(),
8920                 }]
8921         };
8922         check_spends!(spend_tx, tx);
8923         mine_transaction(&nodes[1], &spend_tx);
8924 }
8925
8926 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
8927         // In the first version of the chain::Confirm interface, after a refactor was made to not
8928         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
8929         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
8930         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
8931         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
8932         // spending transaction until height N+1 (or greater). This was due to the way
8933         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
8934         // spending transaction at the height the input transaction was confirmed at, not whether we
8935         // should broadcast a spending transaction at the current height.
8936         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
8937         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
8938         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
8939         // until we learned about an additional block.
8940         //
8941         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
8942         // aren't broadcasting transactions too early (ie not broadcasting them at all).
8943         let chanmon_cfgs = create_chanmon_cfgs(3);
8944         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8945         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8946         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8947         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
8948
8949         create_announced_chan_between_nodes(&nodes, 0, 1);
8950         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
8951         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
8952         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
8953         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
8954
8955         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
8956         check_closed_broadcast!(nodes[1], true);
8957         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8958         check_added_monitors!(nodes[1], 1);
8959         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
8960         assert_eq!(node_txn.len(), 1);
8961
8962         let conf_height = nodes[1].best_block_info().1;
8963         if !test_height_before_timelock {
8964                 connect_blocks(&nodes[1], 24 * 6);
8965         }
8966         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
8967                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
8968         if test_height_before_timelock {
8969                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
8970                 // generate any events or broadcast any transactions
8971                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
8972                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
8973         } else {
8974                 // We should broadcast an HTLC transaction spending our funding transaction first
8975                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
8976                 assert_eq!(spending_txn.len(), 2);
8977                 assert_eq!(spending_txn[0], node_txn[0]);
8978                 check_spends!(spending_txn[1], node_txn[0]);
8979                 // We should also generate a SpendableOutputs event with the to_self output (as its
8980                 // timelock is up).
8981                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
8982                 assert_eq!(descriptor_spend_txn.len(), 1);
8983
8984                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
8985                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
8986                 // additional block built on top of the current chain.
8987                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
8988                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
8989                 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 }]);
8990                 check_added_monitors!(nodes[1], 1);
8991
8992                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8993                 assert!(updates.update_add_htlcs.is_empty());
8994                 assert!(updates.update_fulfill_htlcs.is_empty());
8995                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8996                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8997                 assert!(updates.update_fee.is_none());
8998                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
8999                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9000                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9001         }
9002 }
9003
9004 #[test]
9005 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9006         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9007         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9008 }
9009
9010 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9011         let chanmon_cfgs = create_chanmon_cfgs(2);
9012         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9013         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9014         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9015
9016         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9017
9018         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9019                 .with_features(nodes[1].node.invoice_features());
9020         let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9021
9022         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9023
9024         {
9025                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9026                 check_added_monitors!(nodes[0], 1);
9027                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9028                 assert_eq!(events.len(), 1);
9029                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9030                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9031                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9032         }
9033         expect_pending_htlcs_forwardable!(nodes[1]);
9034         expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9035
9036         {
9037                 // Note that we use a different PaymentId here to allow us to duplicativly pay
9038                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9039                 check_added_monitors!(nodes[0], 1);
9040                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9041                 assert_eq!(events.len(), 1);
9042                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9043                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9044                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9045                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9046                 // assume the second is a privacy attack (no longer particularly relevant
9047                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9048                 // the first HTLC delivered above.
9049         }
9050
9051         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9052         nodes[1].node.process_pending_htlc_forwards();
9053
9054         if test_for_second_fail_panic {
9055                 // Now we go fail back the first HTLC from the user end.
9056                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9057
9058                 let expected_destinations = vec![
9059                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9060                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9061                 ];
9062                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],  expected_destinations);
9063                 nodes[1].node.process_pending_htlc_forwards();
9064
9065                 check_added_monitors!(nodes[1], 1);
9066                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9067                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9068
9069                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9070                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9071                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9072
9073                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9074                 assert_eq!(failure_events.len(), 4);
9075                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9076                 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9077                 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9078                 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9079         } else {
9080                 // Let the second HTLC fail and claim the first
9081                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9082                 nodes[1].node.process_pending_htlc_forwards();
9083
9084                 check_added_monitors!(nodes[1], 1);
9085                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9086                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9087                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9088
9089                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9090
9091                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9092         }
9093 }
9094
9095 #[test]
9096 fn test_dup_htlc_second_fail_panic() {
9097         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9098         // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9099         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9100         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9101         do_test_dup_htlc_second_rejected(true);
9102 }
9103
9104 #[test]
9105 fn test_dup_htlc_second_rejected() {
9106         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9107         // simply reject the second HTLC but are still able to claim the first HTLC.
9108         do_test_dup_htlc_second_rejected(false);
9109 }
9110
9111 #[test]
9112 fn test_inconsistent_mpp_params() {
9113         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9114         // such HTLC and allow the second to stay.
9115         let chanmon_cfgs = create_chanmon_cfgs(4);
9116         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9117         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9118         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9119
9120         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9121         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9122         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9123         let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9124
9125         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9126                 .with_features(nodes[3].node.invoice_features());
9127         let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9128         assert_eq!(route.paths.len(), 2);
9129         route.paths.sort_by(|path_a, _| {
9130                 // Sort the path so that the path through nodes[1] comes first
9131                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9132                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9133         });
9134
9135         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9136
9137         let cur_height = nodes[0].best_block_info().1;
9138         let payment_id = PaymentId([42; 32]);
9139
9140         let session_privs = {
9141                 // We create a fake route here so that we start with three pending HTLCs, which we'll
9142                 // ultimately have, just not right away.
9143                 let mut dup_route = route.clone();
9144                 dup_route.paths.push(route.paths[1].clone());
9145                 nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(our_payment_secret), payment_id, &dup_route).unwrap()
9146         };
9147         nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(our_payment_secret), 15_000_000, cur_height, payment_id, &None, session_privs[0]).unwrap();
9148         check_added_monitors!(nodes[0], 1);
9149
9150         {
9151                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9152                 assert_eq!(events.len(), 1);
9153                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9154         }
9155         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9156
9157         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash, &Some(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9158         check_added_monitors!(nodes[0], 1);
9159
9160         {
9161                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9162                 assert_eq!(events.len(), 1);
9163                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9164
9165                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9166                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9167
9168                 expect_pending_htlcs_forwardable!(nodes[2]);
9169                 check_added_monitors!(nodes[2], 1);
9170
9171                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9172                 assert_eq!(events.len(), 1);
9173                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9174
9175                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9176                 check_added_monitors!(nodes[3], 0);
9177                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9178
9179                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9180                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9181                 // post-payment_secrets) and fail back the new HTLC.
9182         }
9183         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9184         nodes[3].node.process_pending_htlc_forwards();
9185         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9186         nodes[3].node.process_pending_htlc_forwards();
9187
9188         check_added_monitors!(nodes[3], 1);
9189
9190         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9191         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9192         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9193
9194         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }]);
9195         check_added_monitors!(nodes[2], 1);
9196
9197         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9198         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9199         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9200
9201         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9202
9203         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash, &Some(our_payment_secret), 15_000_000, cur_height, payment_id, &None, session_privs[2]).unwrap();
9204         check_added_monitors!(nodes[0], 1);
9205
9206         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9207         assert_eq!(events.len(), 1);
9208         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9209
9210         do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9211         let events = nodes[0].node.get_and_clear_pending_events();
9212         assert_eq!(events.len(), 3);
9213         match events[0] {
9214                 Event::PaymentSent { payment_hash, .. } => { // The payment was abandoned earlier, so the fee paid will be None
9215                         assert_eq!(payment_hash, our_payment_hash);
9216                 },
9217                 _ => panic!("Unexpected event")
9218         }
9219         match events[1] {
9220                 Event::PaymentPathSuccessful { payment_hash, .. } => {
9221                         assert_eq!(payment_hash.unwrap(), our_payment_hash);
9222                 },
9223                 _ => panic!("Unexpected event")
9224         }
9225         match events[2] {
9226                 Event::PaymentPathSuccessful { payment_hash, .. } => {
9227                         assert_eq!(payment_hash.unwrap(), our_payment_hash);
9228                 },
9229                 _ => panic!("Unexpected event")
9230         }
9231 }
9232
9233 #[test]
9234 fn test_keysend_payments_to_public_node() {
9235         let chanmon_cfgs = create_chanmon_cfgs(2);
9236         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9237         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9238         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9239
9240         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9241         let network_graph = nodes[0].network_graph.clone();
9242         let payer_pubkey = nodes[0].node.get_our_node_id();
9243         let payee_pubkey = nodes[1].node.get_our_node_id();
9244         let route_params = RouteParameters {
9245                 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9246                 final_value_msat: 10000,
9247         };
9248         let scorer = test_utils::TestScorer::new();
9249         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9250         let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9251
9252         let test_preimage = PaymentPreimage([42; 32]);
9253         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage), PaymentId(test_preimage.0)).unwrap();
9254         check_added_monitors!(nodes[0], 1);
9255         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9256         assert_eq!(events.len(), 1);
9257         let event = events.pop().unwrap();
9258         let path = vec![&nodes[1]];
9259         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9260         claim_payment(&nodes[0], &path, test_preimage);
9261 }
9262
9263 #[test]
9264 fn test_keysend_payments_to_private_node() {
9265         let chanmon_cfgs = create_chanmon_cfgs(2);
9266         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9267         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9268         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9269
9270         let payer_pubkey = nodes[0].node.get_our_node_id();
9271         let payee_pubkey = nodes[1].node.get_our_node_id();
9272
9273         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
9274         let route_params = RouteParameters {
9275                 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9276                 final_value_msat: 10000,
9277         };
9278         let network_graph = nodes[0].network_graph.clone();
9279         let first_hops = nodes[0].node.list_usable_channels();
9280         let scorer = test_utils::TestScorer::new();
9281         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9282         let route = find_route(
9283                 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9284                 nodes[0].logger, &scorer, &random_seed_bytes
9285         ).unwrap();
9286
9287         let test_preimage = PaymentPreimage([42; 32]);
9288         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage), PaymentId(test_preimage.0)).unwrap();
9289         check_added_monitors!(nodes[0], 1);
9290         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9291         assert_eq!(events.len(), 1);
9292         let event = events.pop().unwrap();
9293         let path = vec![&nodes[1]];
9294         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9295         claim_payment(&nodes[0], &path, test_preimage);
9296 }
9297
9298 #[test]
9299 fn test_double_partial_claim() {
9300         // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9301         // time out, the sender resends only some of the MPP parts, then the user processes the
9302         // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9303         // amount.
9304         let chanmon_cfgs = create_chanmon_cfgs(4);
9305         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9306         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9307         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9308
9309         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9310         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9311         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9312         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9313
9314         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9315         assert_eq!(route.paths.len(), 2);
9316         route.paths.sort_by(|path_a, _| {
9317                 // Sort the path so that the path through nodes[1] comes first
9318                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9319                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9320         });
9321
9322         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9323         // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9324         // amount of time to respond to.
9325
9326         // Connect some blocks to time out the payment
9327         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9328         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9329
9330         let failed_destinations = vec![
9331                 HTLCDestination::FailedPayment { payment_hash },
9332                 HTLCDestination::FailedPayment { payment_hash },
9333         ];
9334         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9335
9336         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
9337
9338         // nodes[1] now retries one of the two paths...
9339         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9340         check_added_monitors!(nodes[0], 2);
9341
9342         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9343         assert_eq!(events.len(), 2);
9344         let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9345         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9346
9347         // At this point nodes[3] has received one half of the payment, and the user goes to handle
9348         // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9349         nodes[3].node.claim_funds(payment_preimage);
9350         check_added_monitors!(nodes[3], 0);
9351         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9352 }
9353
9354 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9355 #[derive(Clone, Copy, PartialEq)]
9356 enum ExposureEvent {
9357         /// Breach occurs at HTLC forwarding (see `send_htlc`)
9358         AtHTLCForward,
9359         /// Breach occurs at HTLC reception (see `update_add_htlc`)
9360         AtHTLCReception,
9361         /// Breach occurs at outbound update_fee (see `send_update_fee`)
9362         AtUpdateFeeOutbound,
9363 }
9364
9365 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9366         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9367         // policy.
9368         //
9369         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9370         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9371         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9372         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9373         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9374         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9375         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9376         // might be available again for HTLC processing once the dust bandwidth has cleared up.
9377
9378         let chanmon_cfgs = create_chanmon_cfgs(2);
9379         let mut config = test_default_channel_config();
9380         config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9381         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9382         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9383         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9384
9385         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9386         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9387         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9388         open_channel.max_accepted_htlcs = 60;
9389         if on_holder_tx {
9390                 open_channel.dust_limit_satoshis = 546;
9391         }
9392         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9393         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9394         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9395
9396         let opt_anchors = false;
9397
9398         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9399
9400         if on_holder_tx {
9401                 let mut node_0_per_peer_lock;
9402                 let mut node_0_peer_state_lock;
9403                 let mut chan = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id);
9404                 chan.holder_dust_limit_satoshis = 546;
9405         }
9406
9407         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9408         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id()));
9409         check_added_monitors!(nodes[1], 1);
9410
9411         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id()));
9412         check_added_monitors!(nodes[0], 1);
9413
9414         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9415         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9416         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9417
9418         let dust_buffer_feerate = {
9419                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9420                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9421                 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9422                 chan.get_dust_buffer_feerate(None) as u64
9423         };
9424         let dust_outbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * htlc_timeout_tx_weight(opt_anchors) / 1000 + open_channel.dust_limit_satoshis - 1) * 1000;
9425         let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9426
9427         let dust_inbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * htlc_success_tx_weight(opt_anchors) / 1000 + open_channel.dust_limit_satoshis - 1) * 1000;
9428         let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9429
9430         let dust_htlc_on_counterparty_tx: u64 = 25;
9431         let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9432
9433         if on_holder_tx {
9434                 if dust_outbound_balance {
9435                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9436                         // Outbound dust balance: 4372 sats
9437                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9438                         for i in 0..dust_outbound_htlc_on_holder_tx {
9439                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9440                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)) { panic!("Unexpected event at dust HTLC {}", i); }
9441                         }
9442                 } else {
9443                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9444                         // Inbound dust balance: 4372 sats
9445                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9446                         for _ in 0..dust_inbound_htlc_on_holder_tx {
9447                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9448                         }
9449                 }
9450         } else {
9451                 if dust_outbound_balance {
9452                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9453                         // Outbound dust balance: 5000 sats
9454                         for i in 0..dust_htlc_on_counterparty_tx {
9455                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9456                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)) { panic!("Unexpected event at dust HTLC {}", i); }
9457                         }
9458                 } else {
9459                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9460                         // Inbound dust balance: 5000 sats
9461                         for _ in 0..dust_htlc_on_counterparty_tx {
9462                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9463                         }
9464                 }
9465         }
9466
9467         let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9468         if exposure_breach_event == ExposureEvent::AtHTLCForward {
9469                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat });
9470                 let mut config = UserConfig::default();
9471                 // With default dust exposure: 5000 sats
9472                 if on_holder_tx {
9473                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9474                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9475                         unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)), true, APIError::ChannelUnavailable { ref err }, assert_eq!(err, &format!("Cannot send value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", if dust_outbound_balance { dust_outbound_overflow } else { dust_inbound_overflow }, config.channel_config.max_dust_htlc_exposure_msat)));
9476                 } else {
9477                         unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)), true, APIError::ChannelUnavailable { ref err }, assert_eq!(err, &format!("Cannot send value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx", dust_overflow, config.channel_config.max_dust_htlc_exposure_msat)));
9478                 }
9479         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9480                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], if on_holder_tx { dust_inbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat });
9481                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9482                 check_added_monitors!(nodes[1], 1);
9483                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9484                 assert_eq!(events.len(), 1);
9485                 let payment_event = SendEvent::from_event(events.remove(0));
9486                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9487                 // With default dust exposure: 5000 sats
9488                 if on_holder_tx {
9489                         // Outbound dust balance: 6399 sats
9490                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9491                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9492                         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", if dust_outbound_balance { dust_outbound_overflow } else { dust_inbound_overflow }, config.channel_config.max_dust_htlc_exposure_msat), 1);
9493                 } else {
9494                         // Outbound dust balance: 5200 sats
9495                         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx", dust_overflow, config.channel_config.max_dust_htlc_exposure_msat), 1);
9496                 }
9497         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9498                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
9499                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
9500                 {
9501                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9502                         *feerate_lock = *feerate_lock * 10;
9503                 }
9504                 nodes[0].node.timer_tick_occurred();
9505                 check_added_monitors!(nodes[0], 1);
9506                 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9507         }
9508
9509         let _ = nodes[0].node.get_and_clear_pending_msg_events();
9510         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9511         added_monitors.clear();
9512 }
9513
9514 #[test]
9515 fn test_max_dust_htlc_exposure() {
9516         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9517         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9518         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9519         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9520         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9521         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9522         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9523         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9524         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9525         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9526         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9527         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
9528 }
9529
9530 #[test]
9531 fn test_non_final_funding_tx() {
9532         let chanmon_cfgs = create_chanmon_cfgs(2);
9533         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9534         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9535         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9536
9537         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9538         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9539         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9540         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9541         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9542
9543         let best_height = nodes[0].node.best_block.read().unwrap().height();
9544
9545         let chan_id = *nodes[0].network_chan_count.borrow();
9546         let events = nodes[0].node.get_and_clear_pending_events();
9547         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9548         assert_eq!(events.len(), 1);
9549         let mut tx = match events[0] {
9550                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9551                         // Timelock the transaction _beyond_ the best client height + 2.
9552                         Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 3), input: vec![input], output: vec![TxOut {
9553                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9554                         }]}
9555                 },
9556                 _ => panic!("Unexpected event"),
9557         };
9558         // Transaction should fail as it's evaluated as non-final for propagation.
9559         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9560                 Err(APIError::APIMisuseError { err }) => {
9561                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9562                 },
9563                 _ => panic!()
9564         }
9565
9566         // However, transaction should be accepted if it's in a +2 headroom from best block.
9567         tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9568         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9569         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9570 }
9571
9572 #[test]
9573 fn accept_busted_but_better_fee() {
9574         // If a peer sends us a fee update that is too low, but higher than our previous channel
9575         // feerate, we should accept it. In the future we may want to consider closing the channel
9576         // later, but for now we only accept the update.
9577         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9578         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9579         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9580         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9581
9582         create_chan_between_nodes(&nodes[0], &nodes[1]);
9583
9584         // Set nodes[1] to expect 5,000 sat/kW.
9585         {
9586                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9587                 *feerate_lock = 5000;
9588         }
9589
9590         // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9591         {
9592                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9593                 *feerate_lock = 1000;
9594         }
9595         nodes[0].node.timer_tick_occurred();
9596         check_added_monitors!(nodes[0], 1);
9597
9598         let events = nodes[0].node.get_and_clear_pending_msg_events();
9599         assert_eq!(events.len(), 1);
9600         match events[0] {
9601                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9602                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9603                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9604                 },
9605                 _ => panic!("Unexpected event"),
9606         };
9607
9608         // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9609         // it.
9610         {
9611                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9612                 *feerate_lock = 2000;
9613         }
9614         nodes[0].node.timer_tick_occurred();
9615         check_added_monitors!(nodes[0], 1);
9616
9617         let events = nodes[0].node.get_and_clear_pending_msg_events();
9618         assert_eq!(events.len(), 1);
9619         match events[0] {
9620                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9621                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9622                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9623                 },
9624                 _ => panic!("Unexpected event"),
9625         };
9626
9627         // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9628         // channel.
9629         {
9630                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9631                 *feerate_lock = 1000;
9632         }
9633         nodes[0].node.timer_tick_occurred();
9634         check_added_monitors!(nodes[0], 1);
9635
9636         let events = nodes[0].node.get_and_clear_pending_msg_events();
9637         assert_eq!(events.len(), 1);
9638         match events[0] {
9639                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9640                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9641                         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9642                                 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() });
9643                         check_closed_broadcast!(nodes[1], true);
9644                         check_added_monitors!(nodes[1], 1);
9645                 },
9646                 _ => panic!("Unexpected event"),
9647         };
9648 }
9649
9650 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9651         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9652         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9653         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9654         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9655         let min_final_cltv_expiry_delta = 120;
9656         let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9657                 min_final_cltv_expiry_delta - 2 };
9658         let recv_value = 100_000;
9659
9660         create_chan_between_nodes(&nodes[0], &nodes[1]);
9661
9662         let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
9663         let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
9664                 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
9665                         Some(recv_value), Some(min_final_cltv_expiry_delta));
9666                 (payment_hash, payment_preimage, payment_secret)
9667         } else {
9668                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
9669                 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
9670         };
9671         let route = get_route!(nodes[0], payment_parameters, recv_value, final_cltv_expiry_delta as u32).unwrap();
9672         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9673         check_added_monitors!(nodes[0], 1);
9674         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9675         assert_eq!(events.len(), 1);
9676         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9677         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9678         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9679         expect_pending_htlcs_forwardable!(nodes[1]);
9680
9681         if valid_delta {
9682                 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
9683                         None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
9684
9685                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9686         } else {
9687                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9688
9689                 check_added_monitors!(nodes[1], 1);
9690
9691                 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9692                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
9693                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
9694
9695                 expect_payment_failed!(nodes[0], payment_hash, true);
9696         }
9697 }
9698
9699 #[test]
9700 fn test_payment_with_custom_min_cltv_expiry_delta() {
9701         do_payment_with_custom_min_final_cltv_expiry(false, false);
9702         do_payment_with_custom_min_final_cltv_expiry(false, true);
9703         do_payment_with_custom_min_final_cltv_expiry(true, false);
9704         do_payment_with_custom_min_final_cltv_expiry(true, true);
9705 }