fc37687926420f4a8b2bb92605ce3588a29fab00
[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, PaymentFailureReason};
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, RecipientOnionFields, 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_with_route(&route, our_payment_hash,
261                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
262         check_added_monitors!(nodes[1], 1);
263
264         let payment_event = {
265                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
266                 assert_eq!(events_1.len(), 1);
267                 SendEvent::from_event(events_1.remove(0))
268         };
269         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
270         assert_eq!(payment_event.msgs.len(), 1);
271
272         // ...now when the messages get delivered everyone should be happy
273         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
274         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
275         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
276         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
277         check_added_monitors!(nodes[0], 1);
278
279         // deliver(1), generate (3):
280         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
281         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
282         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
283         check_added_monitors!(nodes[1], 1);
284
285         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
286         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
287         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
288         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
289         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
290         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
291         assert!(bs_update.update_fee.is_none()); // (4)
292         check_added_monitors!(nodes[1], 1);
293
294         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
295         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
296         assert!(as_update.update_add_htlcs.is_empty()); // (5)
297         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
298         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
299         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
300         assert!(as_update.update_fee.is_none()); // (5)
301         check_added_monitors!(nodes[0], 1);
302
303         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
304         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
305         // only (6) so get_event_msg's assert(len == 1) passes
306         check_added_monitors!(nodes[0], 1);
307
308         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
309         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
310         check_added_monitors!(nodes[1], 1);
311
312         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
313         check_added_monitors!(nodes[0], 1);
314
315         let events_2 = nodes[0].node.get_and_clear_pending_events();
316         assert_eq!(events_2.len(), 1);
317         match events_2[0] {
318                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
319                 _ => panic!("Unexpected event"),
320         }
321
322         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
323         check_added_monitors!(nodes[1], 1);
324 }
325
326 #[test]
327 fn test_update_fee_unordered_raa() {
328         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
329         // crash in an earlier version of the update_fee patch)
330         let chanmon_cfgs = create_chanmon_cfgs(2);
331         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
332         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
333         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
334         create_announced_chan_between_nodes(&nodes, 0, 1);
335
336         // balancing
337         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
338
339         // First nodes[0] generates an update_fee
340         {
341                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
342                 *feerate_lock += 20;
343         }
344         nodes[0].node.timer_tick_occurred();
345         check_added_monitors!(nodes[0], 1);
346
347         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
348         assert_eq!(events_0.len(), 1);
349         let update_msg = match events_0[0] { // (1)
350                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
351                         update_fee.as_ref()
352                 },
353                 _ => panic!("Unexpected event"),
354         };
355
356         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
357
358         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
359         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
360         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
361                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
362         check_added_monitors!(nodes[1], 1);
363
364         let payment_event = {
365                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
366                 assert_eq!(events_1.len(), 1);
367                 SendEvent::from_event(events_1.remove(0))
368         };
369         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
370         assert_eq!(payment_event.msgs.len(), 1);
371
372         // ...now when the messages get delivered everyone should be happy
373         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
374         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
375         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
376         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
377         check_added_monitors!(nodes[0], 1);
378
379         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
380         check_added_monitors!(nodes[1], 1);
381
382         // We can't continue, sadly, because our (1) now has a bogus signature
383 }
384
385 #[test]
386 fn test_multi_flight_update_fee() {
387         let chanmon_cfgs = create_chanmon_cfgs(2);
388         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
389         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
390         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
391         create_announced_chan_between_nodes(&nodes, 0, 1);
392
393         // A                                        B
394         // update_fee/commitment_signed          ->
395         //                                       .- send (1) RAA and (2) commitment_signed
396         // update_fee (never committed)          ->
397         // (3) update_fee                        ->
398         // We have to manually generate the above update_fee, it is allowed by the protocol but we
399         // don't track which updates correspond to which revoke_and_ack responses so we're in
400         // AwaitingRAA mode and will not generate the update_fee yet.
401         //                                       <- (1) RAA delivered
402         // (3) is generated and send (4) CS      -.
403         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
404         // know the per_commitment_point to use for it.
405         //                                       <- (2) commitment_signed delivered
406         // revoke_and_ack                        ->
407         //                                          B should send no response here
408         // (4) commitment_signed delivered       ->
409         //                                       <- RAA/commitment_signed delivered
410         // revoke_and_ack                        ->
411
412         // First nodes[0] generates an update_fee
413         let initial_feerate;
414         {
415                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
416                 initial_feerate = *feerate_lock;
417                 *feerate_lock = initial_feerate + 20;
418         }
419         nodes[0].node.timer_tick_occurred();
420         check_added_monitors!(nodes[0], 1);
421
422         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
423         assert_eq!(events_0.len(), 1);
424         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
425                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
426                         (update_fee.as_ref().unwrap(), commitment_signed)
427                 },
428                 _ => panic!("Unexpected event"),
429         };
430
431         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
432         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
433         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
434         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
435         check_added_monitors!(nodes[1], 1);
436
437         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
438         // transaction:
439         {
440                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
441                 *feerate_lock = initial_feerate + 40;
442         }
443         nodes[0].node.timer_tick_occurred();
444         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
445         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
446
447         // Create the (3) update_fee message that nodes[0] will generate before it does...
448         let mut update_msg_2 = msgs::UpdateFee {
449                 channel_id: update_msg_1.channel_id.clone(),
450                 feerate_per_kw: (initial_feerate + 30) as u32,
451         };
452
453         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
454
455         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
456         // Deliver (3)
457         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
458
459         // Deliver (1), generating (3) and (4)
460         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
461         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
462         check_added_monitors!(nodes[0], 1);
463         assert!(as_second_update.update_add_htlcs.is_empty());
464         assert!(as_second_update.update_fulfill_htlcs.is_empty());
465         assert!(as_second_update.update_fail_htlcs.is_empty());
466         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
467         // Check that the update_fee newly generated matches what we delivered:
468         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
469         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
470
471         // Deliver (2) commitment_signed
472         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
473         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
474         check_added_monitors!(nodes[0], 1);
475         // No commitment_signed so get_event_msg's assert(len == 1) passes
476
477         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
478         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
479         check_added_monitors!(nodes[1], 1);
480
481         // Delever (4)
482         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
483         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
484         check_added_monitors!(nodes[1], 1);
485
486         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
487         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
488         check_added_monitors!(nodes[0], 1);
489
490         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
491         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
492         // No commitment_signed so get_event_msg's assert(len == 1) passes
493         check_added_monitors!(nodes[0], 1);
494
495         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
496         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
497         check_added_monitors!(nodes[1], 1);
498 }
499
500 fn do_test_sanity_on_in_flight_opens(steps: u8) {
501         // Previously, we had issues deserializing channels when we hadn't connected the first block
502         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
503         // serialization round-trips and simply do steps towards opening a channel and then drop the
504         // Node objects.
505
506         let chanmon_cfgs = create_chanmon_cfgs(2);
507         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
508         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
509         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
510
511         if steps & 0b1000_0000 != 0{
512                 let block = Block {
513                         header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
514                         txdata: vec![],
515                 };
516                 connect_block(&nodes[0], &block);
517                 connect_block(&nodes[1], &block);
518         }
519
520         if steps & 0x0f == 0 { return; }
521         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
522         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
523
524         if steps & 0x0f == 1 { return; }
525         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
526         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
527
528         if steps & 0x0f == 2 { return; }
529         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
530
531         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
532
533         if steps & 0x0f == 3 { return; }
534         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
535         check_added_monitors!(nodes[0], 0);
536         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
537
538         if steps & 0x0f == 4 { return; }
539         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
540         {
541                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
542                 assert_eq!(added_monitors.len(), 1);
543                 assert_eq!(added_monitors[0].0, funding_output);
544                 added_monitors.clear();
545         }
546         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
547
548         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
549
550         if steps & 0x0f == 5 { return; }
551         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
552         {
553                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
554                 assert_eq!(added_monitors.len(), 1);
555                 assert_eq!(added_monitors[0].0, funding_output);
556                 added_monitors.clear();
557         }
558
559         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
560         let events_4 = nodes[0].node.get_and_clear_pending_events();
561         assert_eq!(events_4.len(), 0);
562
563         if steps & 0x0f == 6 { return; }
564         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
565
566         if steps & 0x0f == 7 { return; }
567         confirm_transaction_at(&nodes[0], &tx, 2);
568         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
569         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
570         expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
571 }
572
573 #[test]
574 fn test_sanity_on_in_flight_opens() {
575         do_test_sanity_on_in_flight_opens(0);
576         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
577         do_test_sanity_on_in_flight_opens(1);
578         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
579         do_test_sanity_on_in_flight_opens(2);
580         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
581         do_test_sanity_on_in_flight_opens(3);
582         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
583         do_test_sanity_on_in_flight_opens(4);
584         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
585         do_test_sanity_on_in_flight_opens(5);
586         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
587         do_test_sanity_on_in_flight_opens(6);
588         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
589         do_test_sanity_on_in_flight_opens(7);
590         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
591         do_test_sanity_on_in_flight_opens(8);
592         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
593 }
594
595 #[test]
596 fn test_update_fee_vanilla() {
597         let chanmon_cfgs = create_chanmon_cfgs(2);
598         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
599         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
600         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
601         create_announced_chan_between_nodes(&nodes, 0, 1);
602
603         {
604                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
605                 *feerate_lock += 25;
606         }
607         nodes[0].node.timer_tick_occurred();
608         check_added_monitors!(nodes[0], 1);
609
610         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
611         assert_eq!(events_0.len(), 1);
612         let (update_msg, commitment_signed) = match events_0[0] {
613                         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 } } => {
614                         (update_fee.as_ref(), commitment_signed)
615                 },
616                 _ => panic!("Unexpected event"),
617         };
618         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
619
620         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
621         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
622         check_added_monitors!(nodes[1], 1);
623
624         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
625         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
626         check_added_monitors!(nodes[0], 1);
627
628         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
629         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
630         // No commitment_signed so get_event_msg's assert(len == 1) passes
631         check_added_monitors!(nodes[0], 1);
632
633         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
634         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
635         check_added_monitors!(nodes[1], 1);
636 }
637
638 #[test]
639 fn test_update_fee_that_funder_cannot_afford() {
640         let chanmon_cfgs = create_chanmon_cfgs(2);
641         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
642         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
643         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
644         let channel_value = 5000;
645         let push_sats = 700;
646         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000);
647         let channel_id = chan.2;
648         let secp_ctx = Secp256k1::new();
649         let default_config = UserConfig::default();
650         let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
651
652         let opt_anchors = false;
653
654         // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
655         // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
656         // calculate two different feerates here - the expected local limit as well as the expected
657         // remote limit.
658         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;
659         let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
660         {
661                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
662                 *feerate_lock = feerate;
663         }
664         nodes[0].node.timer_tick_occurred();
665         check_added_monitors!(nodes[0], 1);
666         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
667
668         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
669
670         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
671
672         // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
673         {
674                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
675
676                 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
677                 assert_eq!(commitment_tx.output.len(), 2);
678                 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
679                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
680                 actual_fee = channel_value - actual_fee;
681                 assert_eq!(total_fee, actual_fee);
682         }
683
684         {
685                 // Increment the feerate by a small constant, accounting for rounding errors
686                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
687                 *feerate_lock += 4;
688         }
689         nodes[0].node.timer_tick_occurred();
690         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
691         check_added_monitors!(nodes[0], 0);
692
693         const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
694
695         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
696         // needed to sign the new commitment tx and (2) sign the new commitment tx.
697         let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
698                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
699                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
700                 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
701                 let chan_signer = local_chan.get_signer();
702                 let pubkeys = chan_signer.pubkeys();
703                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
704                  pubkeys.funding_pubkey)
705         };
706         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
707                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
708                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
709                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
710                 let chan_signer = remote_chan.get_signer();
711                 let pubkeys = chan_signer.pubkeys();
712                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
713                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
714                  pubkeys.funding_pubkey)
715         };
716
717         // Assemble the set of keys we can use for signatures for our commitment_signed message.
718         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
719                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
720
721         let res = {
722                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
723                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
724                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
725                 let local_chan_signer = local_chan.get_signer();
726                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
727                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
728                         INITIAL_COMMITMENT_NUMBER - 1,
729                         push_sats,
730                         channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
731                         opt_anchors, local_funding, remote_funding,
732                         commit_tx_keys.clone(),
733                         non_buffer_feerate + 4,
734                         &mut htlcs,
735                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
736                 );
737                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
738         };
739
740         let commit_signed_msg = msgs::CommitmentSigned {
741                 channel_id: chan.2,
742                 signature: res.0,
743                 htlc_signatures: res.1,
744                 #[cfg(taproot)]
745                 partial_signature_with_nonce: None,
746         };
747
748         let update_fee = msgs::UpdateFee {
749                 channel_id: chan.2,
750                 feerate_per_kw: non_buffer_feerate + 4,
751         };
752
753         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
754
755         //While producing the commitment_signed response after handling a received update_fee request the
756         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
757         //Should produce and error.
758         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
759         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
760         check_added_monitors!(nodes[1], 1);
761         check_closed_broadcast!(nodes[1], true);
762         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
763 }
764
765 #[test]
766 fn test_update_fee_with_fundee_update_add_htlc() {
767         let chanmon_cfgs = create_chanmon_cfgs(2);
768         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
769         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
770         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
771         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
772
773         // balancing
774         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
775
776         {
777                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
778                 *feerate_lock += 20;
779         }
780         nodes[0].node.timer_tick_occurred();
781         check_added_monitors!(nodes[0], 1);
782
783         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
784         assert_eq!(events_0.len(), 1);
785         let (update_msg, commitment_signed) = match events_0[0] {
786                         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 } } => {
787                         (update_fee.as_ref(), commitment_signed)
788                 },
789                 _ => panic!("Unexpected event"),
790         };
791         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
792         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
793         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
794         check_added_monitors!(nodes[1], 1);
795
796         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
797
798         // nothing happens since node[1] is in AwaitingRemoteRevoke
799         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
800                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
801         {
802                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
803                 assert_eq!(added_monitors.len(), 0);
804                 added_monitors.clear();
805         }
806         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
807         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
808         // node[1] has nothing to do
809
810         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
811         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
812         check_added_monitors!(nodes[0], 1);
813
814         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
815         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
816         // No commitment_signed so get_event_msg's assert(len == 1) passes
817         check_added_monitors!(nodes[0], 1);
818         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
819         check_added_monitors!(nodes[1], 1);
820         // AwaitingRemoteRevoke ends here
821
822         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
823         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
824         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
825         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
826         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
827         assert_eq!(commitment_update.update_fee.is_none(), true);
828
829         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
830         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
831         check_added_monitors!(nodes[0], 1);
832         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
833
834         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
835         check_added_monitors!(nodes[1], 1);
836         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
837
838         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
839         check_added_monitors!(nodes[1], 1);
840         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
841         // No commitment_signed so get_event_msg's assert(len == 1) passes
842
843         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
844         check_added_monitors!(nodes[0], 1);
845         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
846
847         expect_pending_htlcs_forwardable!(nodes[0]);
848
849         let events = nodes[0].node.get_and_clear_pending_events();
850         assert_eq!(events.len(), 1);
851         match events[0] {
852                 Event::PaymentClaimable { .. } => { },
853                 _ => panic!("Unexpected event"),
854         };
855
856         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
857
858         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
859         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
860         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
861         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
862         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
863 }
864
865 #[test]
866 fn test_update_fee() {
867         let chanmon_cfgs = create_chanmon_cfgs(2);
868         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
869         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
870         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
871         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
872         let channel_id = chan.2;
873
874         // A                                        B
875         // (1) update_fee/commitment_signed      ->
876         //                                       <- (2) revoke_and_ack
877         //                                       .- send (3) commitment_signed
878         // (4) update_fee/commitment_signed      ->
879         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
880         //                                       <- (3) commitment_signed delivered
881         // send (6) revoke_and_ack               -.
882         //                                       <- (5) deliver revoke_and_ack
883         // (6) deliver revoke_and_ack            ->
884         //                                       .- send (7) commitment_signed in response to (4)
885         //                                       <- (7) deliver commitment_signed
886         // revoke_and_ack                        ->
887
888         // Create and deliver (1)...
889         let feerate;
890         {
891                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
892                 feerate = *feerate_lock;
893                 *feerate_lock = feerate + 20;
894         }
895         nodes[0].node.timer_tick_occurred();
896         check_added_monitors!(nodes[0], 1);
897
898         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
899         assert_eq!(events_0.len(), 1);
900         let (update_msg, commitment_signed) = match events_0[0] {
901                         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 } } => {
902                         (update_fee.as_ref(), commitment_signed)
903                 },
904                 _ => panic!("Unexpected event"),
905         };
906         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
907
908         // Generate (2) and (3):
909         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
910         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
911         check_added_monitors!(nodes[1], 1);
912
913         // Deliver (2):
914         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
915         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
916         check_added_monitors!(nodes[0], 1);
917
918         // Create and deliver (4)...
919         {
920                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
921                 *feerate_lock = feerate + 30;
922         }
923         nodes[0].node.timer_tick_occurred();
924         check_added_monitors!(nodes[0], 1);
925         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
926         assert_eq!(events_0.len(), 1);
927         let (update_msg, commitment_signed) = match events_0[0] {
928                         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 } } => {
929                         (update_fee.as_ref(), commitment_signed)
930                 },
931                 _ => panic!("Unexpected event"),
932         };
933
934         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
935         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
936         check_added_monitors!(nodes[1], 1);
937         // ... creating (5)
938         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
939         // No commitment_signed so get_event_msg's assert(len == 1) passes
940
941         // Handle (3), creating (6):
942         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
943         check_added_monitors!(nodes[0], 1);
944         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
945         // No commitment_signed so get_event_msg's assert(len == 1) passes
946
947         // Deliver (5):
948         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
949         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
950         check_added_monitors!(nodes[0], 1);
951
952         // Deliver (6), creating (7):
953         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
954         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
955         assert!(commitment_update.update_add_htlcs.is_empty());
956         assert!(commitment_update.update_fulfill_htlcs.is_empty());
957         assert!(commitment_update.update_fail_htlcs.is_empty());
958         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
959         assert!(commitment_update.update_fee.is_none());
960         check_added_monitors!(nodes[1], 1);
961
962         // Deliver (7)
963         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
964         check_added_monitors!(nodes[0], 1);
965         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
966         // No commitment_signed so get_event_msg's assert(len == 1) passes
967
968         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
969         check_added_monitors!(nodes[1], 1);
970         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
971
972         assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
973         assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
974         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
975         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
976         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
977 }
978
979 #[test]
980 fn fake_network_test() {
981         // Simple test which builds a network of ChannelManagers, connects them to each other, and
982         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
983         let chanmon_cfgs = create_chanmon_cfgs(4);
984         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
985         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
986         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
987
988         // Create some initial channels
989         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
990         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
991         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
992
993         // Rebalance the network a bit by relaying one payment through all the channels...
994         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
995         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
996         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
997         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
998
999         // Send some more payments
1000         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
1001         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
1002         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
1003
1004         // Test failure packets
1005         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1006         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1007
1008         // Add a new channel that skips 3
1009         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1010
1011         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1012         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1013         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1014         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1015         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1016         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1017         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1018
1019         // Do some rebalance loop payments, simultaneously
1020         let mut hops = Vec::with_capacity(3);
1021         hops.push(RouteHop {
1022                 pubkey: nodes[2].node.get_our_node_id(),
1023                 node_features: NodeFeatures::empty(),
1024                 short_channel_id: chan_2.0.contents.short_channel_id,
1025                 channel_features: ChannelFeatures::empty(),
1026                 fee_msat: 0,
1027                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1028         });
1029         hops.push(RouteHop {
1030                 pubkey: nodes[3].node.get_our_node_id(),
1031                 node_features: NodeFeatures::empty(),
1032                 short_channel_id: chan_3.0.contents.short_channel_id,
1033                 channel_features: ChannelFeatures::empty(),
1034                 fee_msat: 0,
1035                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1036         });
1037         hops.push(RouteHop {
1038                 pubkey: nodes[1].node.get_our_node_id(),
1039                 node_features: nodes[1].node.node_features(),
1040                 short_channel_id: chan_4.0.contents.short_channel_id,
1041                 channel_features: nodes[1].node.channel_features(),
1042                 fee_msat: 1000000,
1043                 cltv_expiry_delta: TEST_FINAL_CLTV,
1044         });
1045         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;
1046         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;
1047         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;
1048
1049         let mut hops = Vec::with_capacity(3);
1050         hops.push(RouteHop {
1051                 pubkey: nodes[3].node.get_our_node_id(),
1052                 node_features: NodeFeatures::empty(),
1053                 short_channel_id: chan_4.0.contents.short_channel_id,
1054                 channel_features: ChannelFeatures::empty(),
1055                 fee_msat: 0,
1056                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1057         });
1058         hops.push(RouteHop {
1059                 pubkey: nodes[2].node.get_our_node_id(),
1060                 node_features: NodeFeatures::empty(),
1061                 short_channel_id: chan_3.0.contents.short_channel_id,
1062                 channel_features: ChannelFeatures::empty(),
1063                 fee_msat: 0,
1064                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1065         });
1066         hops.push(RouteHop {
1067                 pubkey: nodes[1].node.get_our_node_id(),
1068                 node_features: nodes[1].node.node_features(),
1069                 short_channel_id: chan_2.0.contents.short_channel_id,
1070                 channel_features: nodes[1].node.channel_features(),
1071                 fee_msat: 1000000,
1072                 cltv_expiry_delta: TEST_FINAL_CLTV,
1073         });
1074         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;
1075         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;
1076         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;
1077
1078         // Claim the rebalances...
1079         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1080         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1081
1082         // Close down the channels...
1083         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1084         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1085         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1086         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1087         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1088         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1089         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1090         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1091         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1092         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1093         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1094         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1095 }
1096
1097 #[test]
1098 fn holding_cell_htlc_counting() {
1099         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1100         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1101         // commitment dance rounds.
1102         let chanmon_cfgs = create_chanmon_cfgs(3);
1103         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1104         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1105         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1106         create_announced_chan_between_nodes(&nodes, 0, 1);
1107         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1108
1109         let mut payments = Vec::new();
1110         for _ in 0..crate::ln::channel::OUR_MAX_HTLCS {
1111                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1112                 nodes[1].node.send_payment_with_route(&route, payment_hash,
1113                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1114                 payments.push((payment_preimage, payment_hash));
1115         }
1116         check_added_monitors!(nodes[1], 1);
1117
1118         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1119         assert_eq!(events.len(), 1);
1120         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1121         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1122
1123         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1124         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1125         // another HTLC.
1126         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1127         {
1128                 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, payment_hash_1,
1129                                 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)
1130                         ), true, APIError::ChannelUnavailable { ref err },
1131                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1132                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1133                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
1134         }
1135
1136         // This should also be true if we try to forward a payment.
1137         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1138         {
1139                 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1140                         RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1141                 check_added_monitors!(nodes[0], 1);
1142         }
1143
1144         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1145         assert_eq!(events.len(), 1);
1146         let payment_event = SendEvent::from_event(events.pop().unwrap());
1147         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1148
1149         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1150         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1151         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1152         // fails), the second will process the resulting failure and fail the HTLC backward.
1153         expect_pending_htlcs_forwardable!(nodes[1]);
1154         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 }]);
1155         check_added_monitors!(nodes[1], 1);
1156
1157         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1158         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1159         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1160
1161         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1162
1163         // Now forward all the pending HTLCs and claim them back
1164         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1165         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1166         check_added_monitors!(nodes[2], 1);
1167
1168         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1169         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1170         check_added_monitors!(nodes[1], 1);
1171         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1172
1173         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1174         check_added_monitors!(nodes[1], 1);
1175         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1176
1177         for ref update in as_updates.update_add_htlcs.iter() {
1178                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1179         }
1180         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1181         check_added_monitors!(nodes[2], 1);
1182         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1183         check_added_monitors!(nodes[2], 1);
1184         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1185
1186         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1187         check_added_monitors!(nodes[1], 1);
1188         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1189         check_added_monitors!(nodes[1], 1);
1190         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1191
1192         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1193         check_added_monitors!(nodes[2], 1);
1194
1195         expect_pending_htlcs_forwardable!(nodes[2]);
1196
1197         let events = nodes[2].node.get_and_clear_pending_events();
1198         assert_eq!(events.len(), payments.len());
1199         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1200                 match event {
1201                         &Event::PaymentClaimable { ref payment_hash, .. } => {
1202                                 assert_eq!(*payment_hash, *hash);
1203                         },
1204                         _ => panic!("Unexpected event"),
1205                 };
1206         }
1207
1208         for (preimage, _) in payments.drain(..) {
1209                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1210         }
1211
1212         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1213 }
1214
1215 #[test]
1216 fn duplicate_htlc_test() {
1217         // Test that we accept duplicate payment_hash HTLCs across the network and that
1218         // claiming/failing them are all separate and don't affect each other
1219         let chanmon_cfgs = create_chanmon_cfgs(6);
1220         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1221         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1222         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1223
1224         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1225         create_announced_chan_between_nodes(&nodes, 0, 3);
1226         create_announced_chan_between_nodes(&nodes, 1, 3);
1227         create_announced_chan_between_nodes(&nodes, 2, 3);
1228         create_announced_chan_between_nodes(&nodes, 3, 4);
1229         create_announced_chan_between_nodes(&nodes, 3, 5);
1230
1231         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1232
1233         *nodes[0].network_payment_count.borrow_mut() -= 1;
1234         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1235
1236         *nodes[0].network_payment_count.borrow_mut() -= 1;
1237         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1238
1239         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1240         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1241         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1242 }
1243
1244 #[test]
1245 fn test_duplicate_htlc_different_direction_onchain() {
1246         // Test that ChannelMonitor doesn't generate 2 preimage txn
1247         // when we have 2 HTLCs with same preimage that go across a node
1248         // in opposite directions, even with the same payment secret.
1249         let chanmon_cfgs = create_chanmon_cfgs(2);
1250         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1251         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1252         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1253
1254         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1255
1256         // balancing
1257         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1258
1259         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1260
1261         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1262         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1263         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1264
1265         // Provide preimage to node 0 by claiming payment
1266         nodes[0].node.claim_funds(payment_preimage);
1267         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1268         check_added_monitors!(nodes[0], 1);
1269
1270         // Broadcast node 1 commitment txn
1271         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1272
1273         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1274         let mut has_both_htlcs = 0; // check htlcs match ones committed
1275         for outp in remote_txn[0].output.iter() {
1276                 if outp.value == 800_000 / 1000 {
1277                         has_both_htlcs += 1;
1278                 } else if outp.value == 900_000 / 1000 {
1279                         has_both_htlcs += 1;
1280                 }
1281         }
1282         assert_eq!(has_both_htlcs, 2);
1283
1284         mine_transaction(&nodes[0], &remote_txn[0]);
1285         check_added_monitors!(nodes[0], 1);
1286         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1287         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1288
1289         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1290         assert_eq!(claim_txn.len(), 3);
1291
1292         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1293         check_spends!(claim_txn[1], remote_txn[0]);
1294         check_spends!(claim_txn[2], remote_txn[0]);
1295         let preimage_tx = &claim_txn[0];
1296         let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1297                 (&claim_txn[1], &claim_txn[2])
1298         } else {
1299                 (&claim_txn[2], &claim_txn[1])
1300         };
1301
1302         assert_eq!(preimage_tx.input.len(), 1);
1303         assert_eq!(preimage_bump_tx.input.len(), 1);
1304
1305         assert_eq!(preimage_tx.input.len(), 1);
1306         assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1307         assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1308
1309         assert_eq!(timeout_tx.input.len(), 1);
1310         assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1311         check_spends!(timeout_tx, remote_txn[0]);
1312         assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1313
1314         let events = nodes[0].node.get_and_clear_pending_msg_events();
1315         assert_eq!(events.len(), 3);
1316         for e in events {
1317                 match e {
1318                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1319                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1320                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1321                                 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1322                         },
1323                         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, .. } } => {
1324                                 assert!(update_add_htlcs.is_empty());
1325                                 assert!(update_fail_htlcs.is_empty());
1326                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1327                                 assert!(update_fail_malformed_htlcs.is_empty());
1328                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1329                         },
1330                         _ => panic!("Unexpected event"),
1331                 }
1332         }
1333 }
1334
1335 #[test]
1336 fn test_basic_channel_reserve() {
1337         let chanmon_cfgs = create_chanmon_cfgs(2);
1338         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1339         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1340         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1341         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1342
1343         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1344         let channel_reserve = chan_stat.channel_reserve_msat;
1345
1346         // The 2* and +1 are for the fee spike reserve.
1347         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));
1348         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1349         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1350         let err = nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1351                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1352         match err {
1353                 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1354                         match &fails[0] {
1355                                 &APIError::ChannelUnavailable{ref err} =>
1356                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1357                                 _ => panic!("Unexpected error variant"),
1358                         }
1359                 },
1360                 _ => panic!("Unexpected error variant"),
1361         }
1362         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1363         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put our balance under counterparty-announced channel reserve value", 1);
1364
1365         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1366 }
1367
1368 #[test]
1369 fn test_fee_spike_violation_fails_htlc() {
1370         let chanmon_cfgs = create_chanmon_cfgs(2);
1371         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1372         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1373         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1374         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1375
1376         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1377         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1378         let secp_ctx = Secp256k1::new();
1379         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1380
1381         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1382
1383         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1384         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1385                 3460001, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1386         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1387         let msg = msgs::UpdateAddHTLC {
1388                 channel_id: chan.2,
1389                 htlc_id: 0,
1390                 amount_msat: htlc_msat,
1391                 payment_hash: payment_hash,
1392                 cltv_expiry: htlc_cltv,
1393                 onion_routing_packet: onion_packet,
1394         };
1395
1396         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1397
1398         // Now manually create the commitment_signed message corresponding to the update_add
1399         // nodes[0] just sent. In the code for construction of this message, "local" refers
1400         // to the sender of the message, and "remote" refers to the receiver.
1401
1402         let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1403
1404         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1405
1406         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1407         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1408         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1409                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1410                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1411                 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1412                 let chan_signer = local_chan.get_signer();
1413                 // Make the signer believe we validated another commitment, so we can release the secret
1414                 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1415
1416                 let pubkeys = chan_signer.pubkeys();
1417                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1418                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1419                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1420                  chan_signer.pubkeys().funding_pubkey)
1421         };
1422         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1423                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1424                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1425                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1426                 let chan_signer = remote_chan.get_signer();
1427                 let pubkeys = chan_signer.pubkeys();
1428                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1429                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1430                  chan_signer.pubkeys().funding_pubkey)
1431         };
1432
1433         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1434         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1435                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1436
1437         // Build the remote commitment transaction so we can sign it, and then later use the
1438         // signature for the commitment_signed message.
1439         let local_chan_balance = 1313;
1440
1441         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1442                 offered: false,
1443                 amount_msat: 3460001,
1444                 cltv_expiry: htlc_cltv,
1445                 payment_hash,
1446                 transaction_output_index: Some(1),
1447         };
1448
1449         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1450
1451         let res = {
1452                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1453                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1454                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
1455                 let local_chan_signer = local_chan.get_signer();
1456                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1457                         commitment_number,
1458                         95000,
1459                         local_chan_balance,
1460                         local_chan.opt_anchors(), local_funding, remote_funding,
1461                         commit_tx_keys.clone(),
1462                         feerate_per_kw,
1463                         &mut vec![(accepted_htlc_info, ())],
1464                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1465                 );
1466                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1467         };
1468
1469         let commit_signed_msg = msgs::CommitmentSigned {
1470                 channel_id: chan.2,
1471                 signature: res.0,
1472                 htlc_signatures: res.1,
1473                 #[cfg(taproot)]
1474                 partial_signature_with_nonce: None,
1475         };
1476
1477         // Send the commitment_signed message to the nodes[1].
1478         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1479         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1480
1481         // Send the RAA to nodes[1].
1482         let raa_msg = msgs::RevokeAndACK {
1483                 channel_id: chan.2,
1484                 per_commitment_secret: local_secret,
1485                 next_per_commitment_point: next_local_point,
1486                 #[cfg(taproot)]
1487                 next_local_nonce: None,
1488         };
1489         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1490
1491         let events = nodes[1].node.get_and_clear_pending_msg_events();
1492         assert_eq!(events.len(), 1);
1493         // Make sure the HTLC failed in the way we expect.
1494         match events[0] {
1495                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1496                         assert_eq!(update_fail_htlcs.len(), 1);
1497                         update_fail_htlcs[0].clone()
1498                 },
1499                 _ => panic!("Unexpected event"),
1500         };
1501         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1502                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1503
1504         check_added_monitors!(nodes[1], 2);
1505 }
1506
1507 #[test]
1508 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1509         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1510         // Set the fee rate for the channel very high, to the point where the fundee
1511         // sending any above-dust amount would result in a channel reserve violation.
1512         // In this test we check that we would be prevented from sending an HTLC in
1513         // this situation.
1514         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1515         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1516         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1517         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1518         let default_config = UserConfig::default();
1519         let opt_anchors = false;
1520
1521         let mut push_amt = 100_000_000;
1522         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1523
1524         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1525
1526         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1527
1528         // Sending exactly enough to hit the reserve amount should be accepted
1529         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1530                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1531         }
1532
1533         // However one more HTLC should be significantly over the reserve amount and fail.
1534         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1535         unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1536                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1537                 ), true, APIError::ChannelUnavailable { ref err },
1538                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1539         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1540         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);
1541 }
1542
1543 #[test]
1544 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1545         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1546         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1547         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1548         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1549         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1550         let default_config = UserConfig::default();
1551         let opt_anchors = false;
1552
1553         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1554         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1555         // transaction fee with 0 HTLCs (183 sats)).
1556         let mut push_amt = 100_000_000;
1557         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1558         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1559         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1560
1561         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1562         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1563                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1564         }
1565
1566         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1567         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1568         let secp_ctx = Secp256k1::new();
1569         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1570         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1571         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1572         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1573                 700_000, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1574         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1575         let msg = msgs::UpdateAddHTLC {
1576                 channel_id: chan.2,
1577                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1578                 amount_msat: htlc_msat,
1579                 payment_hash: payment_hash,
1580                 cltv_expiry: htlc_cltv,
1581                 onion_routing_packet: onion_packet,
1582         };
1583
1584         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1585         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1586         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);
1587         assert_eq!(nodes[0].node.list_channels().len(), 0);
1588         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1589         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1590         check_added_monitors!(nodes[0], 1);
1591         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() });
1592 }
1593
1594 #[test]
1595 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1596         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1597         // calculating our commitment transaction fee (this was previously broken).
1598         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1599         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1600
1601         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1602         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1603         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1604         let default_config = UserConfig::default();
1605         let opt_anchors = false;
1606
1607         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1608         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1609         // transaction fee with 0 HTLCs (183 sats)).
1610         let mut push_amt = 100_000_000;
1611         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1612         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1613         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1614
1615         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1616                 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1617         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1618         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1619         // commitment transaction fee.
1620         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1621
1622         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1623         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1624                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1625         }
1626
1627         // One more than the dust amt should fail, however.
1628         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1629         unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1630                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1631                 ), true, APIError::ChannelUnavailable { ref err },
1632                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1633 }
1634
1635 #[test]
1636 fn test_chan_init_feerate_unaffordability() {
1637         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1638         // channel reserve and feerate requirements.
1639         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1640         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1641         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1642         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1643         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1644         let default_config = UserConfig::default();
1645         let opt_anchors = false;
1646
1647         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1648         // HTLC.
1649         let mut push_amt = 100_000_000;
1650         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1651         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1652                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1653
1654         // During open, we don't have a "counterparty channel reserve" to check against, so that
1655         // requirement only comes into play on the open_channel handling side.
1656         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1657         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1658         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1659         open_channel_msg.push_msat += 1;
1660         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1661
1662         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1663         assert_eq!(msg_events.len(), 1);
1664         match msg_events[0] {
1665                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1666                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1667                 },
1668                 _ => panic!("Unexpected event"),
1669         }
1670 }
1671
1672 #[test]
1673 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1674         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1675         // calculating our counterparty's commitment transaction fee (this was previously broken).
1676         let chanmon_cfgs = create_chanmon_cfgs(2);
1677         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1678         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1679         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1680         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1681
1682         let payment_amt = 46000; // Dust amount
1683         // In the previous code, these first four payments would succeed.
1684         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1685         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1686         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1687         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1688
1689         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1690         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1691         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1692         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1693         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1694         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1695
1696         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1697         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1698         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1699         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1700 }
1701
1702 #[test]
1703 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1704         let chanmon_cfgs = create_chanmon_cfgs(3);
1705         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1706         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1707         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1708         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1709         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1710
1711         let feemsat = 239;
1712         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1713         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1714         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1715         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
1716
1717         // Add a 2* and +1 for the fee spike reserve.
1718         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1719         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;
1720         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1721
1722         // Add a pending HTLC.
1723         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1724         let payment_event_1 = {
1725                 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1726                         RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1727                 check_added_monitors!(nodes[0], 1);
1728
1729                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1730                 assert_eq!(events.len(), 1);
1731                 SendEvent::from_event(events.remove(0))
1732         };
1733         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1734
1735         // Attempt to trigger a channel reserve violation --> payment failure.
1736         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1737         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;
1738         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1739         let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1740
1741         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1742         let secp_ctx = Secp256k1::new();
1743         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1744         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1745         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1746         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
1747                 &route_2.paths[0], recv_value_2, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
1748         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1749         let msg = msgs::UpdateAddHTLC {
1750                 channel_id: chan.2,
1751                 htlc_id: 1,
1752                 amount_msat: htlc_msat + 1,
1753                 payment_hash: our_payment_hash_1,
1754                 cltv_expiry: htlc_cltv,
1755                 onion_routing_packet: onion_packet,
1756         };
1757
1758         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1759         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1760         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1761         assert_eq!(nodes[1].node.list_channels().len(), 1);
1762         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1763         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1764         check_added_monitors!(nodes[1], 1);
1765         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1766 }
1767
1768 #[test]
1769 fn test_inbound_outbound_capacity_is_not_zero() {
1770         let chanmon_cfgs = create_chanmon_cfgs(2);
1771         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1772         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1773         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1774         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1775         let channels0 = node_chanmgrs[0].list_channels();
1776         let channels1 = node_chanmgrs[1].list_channels();
1777         let default_config = UserConfig::default();
1778         assert_eq!(channels0.len(), 1);
1779         assert_eq!(channels1.len(), 1);
1780
1781         let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1782         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1783         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1784
1785         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1786         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1787 }
1788
1789 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1790         (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1791 }
1792
1793 #[test]
1794 fn test_channel_reserve_holding_cell_htlcs() {
1795         let chanmon_cfgs = create_chanmon_cfgs(3);
1796         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1797         // When this test was written, the default base fee floated based on the HTLC count.
1798         // It is now fixed, so we simply set the fee to the expected value here.
1799         let mut config = test_default_channel_config();
1800         config.channel_config.forwarding_fee_base_msat = 239;
1801         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1802         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1803         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1804         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1805
1806         let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1807         let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1808
1809         let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1810         let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1811
1812         macro_rules! expect_forward {
1813                 ($node: expr) => {{
1814                         let mut events = $node.node.get_and_clear_pending_msg_events();
1815                         assert_eq!(events.len(), 1);
1816                         check_added_monitors!($node, 1);
1817                         let payment_event = SendEvent::from_event(events.remove(0));
1818                         payment_event
1819                 }}
1820         }
1821
1822         let feemsat = 239; // set above
1823         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1824         let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1825         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_1.2);
1826
1827         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1828
1829         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
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 (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);
1834                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1835                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1836
1837                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1838                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1839                         ), true, APIError::ChannelUnavailable { ref err },
1840                         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)));
1841                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1842                 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);
1843         }
1844
1845         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1846         // nodes[0]'s wealth
1847         loop {
1848                 let amt_msat = recv_value_0 + total_fee_msat;
1849                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1850                 // Also, ensure that each payment has enough to be over the dust limit to
1851                 // ensure it'll be included in each commit tx fee calculation.
1852                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1853                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1854                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1855                         break;
1856                 }
1857
1858                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1859                         .with_features(nodes[2].node.invoice_features()).with_max_channel_saturation_power_of_half(0);
1860                 let route = get_route!(nodes[0], payment_params, recv_value_0, TEST_FINAL_CLTV).unwrap();
1861                 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1862                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1863
1864                 let (stat01_, stat11_, stat12_, stat22_) = (
1865                         get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1866                         get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1867                         get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1868                         get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1869                 );
1870
1871                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1872                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1873                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1874                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1875                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1876         }
1877
1878         // adding pending output.
1879         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1880         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1881         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1882         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1883         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1884         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1885         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1886         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1887         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1888         // policy.
1889         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1890         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1891         let amt_msat_1 = recv_value_1 + total_fee_msat;
1892
1893         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);
1894         let payment_event_1 = {
1895                 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1896                         RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1897                 check_added_monitors!(nodes[0], 1);
1898
1899                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1900                 assert_eq!(events.len(), 1);
1901                 SendEvent::from_event(events.remove(0))
1902         };
1903         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1904
1905         // channel reserve test with htlc pending output > 0
1906         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1907         {
1908                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1909                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1910                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1911                         ), true, APIError::ChannelUnavailable { ref err },
1912                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1913                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1914         }
1915
1916         // split the rest to test holding cell
1917         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1918         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1919         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1920         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1921         {
1922                 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1923                 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);
1924         }
1925
1926         // now see if they go through on both sides
1927         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);
1928         // but this will stuck in the holding cell
1929         nodes[0].node.send_payment_with_route(&route_21, our_payment_hash_21,
1930                 RecipientOnionFields::secret_only(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1931         check_added_monitors!(nodes[0], 0);
1932         let events = nodes[0].node.get_and_clear_pending_events();
1933         assert_eq!(events.len(), 0);
1934
1935         // test with outbound holding cell amount > 0
1936         {
1937                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1938                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1939                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1940                         ), true, APIError::ChannelUnavailable { ref err },
1941                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1942                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1943                 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put our balance under counterparty-announced channel reserve value", 2);
1944         }
1945
1946         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);
1947         // this will also stuck in the holding cell
1948         nodes[0].node.send_payment_with_route(&route_22, our_payment_hash_22,
1949                 RecipientOnionFields::secret_only(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1950         check_added_monitors!(nodes[0], 0);
1951         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1952         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1953
1954         // flush the pending htlc
1955         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1956         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1957         check_added_monitors!(nodes[1], 1);
1958
1959         // the pending htlc should be promoted to committed
1960         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1961         check_added_monitors!(nodes[0], 1);
1962         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1963
1964         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1965         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1966         // No commitment_signed so get_event_msg's assert(len == 1) passes
1967         check_added_monitors!(nodes[0], 1);
1968
1969         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1970         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1971         check_added_monitors!(nodes[1], 1);
1972
1973         expect_pending_htlcs_forwardable!(nodes[1]);
1974
1975         let ref payment_event_11 = expect_forward!(nodes[1]);
1976         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1977         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1978
1979         expect_pending_htlcs_forwardable!(nodes[2]);
1980         expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1981
1982         // flush the htlcs in the holding cell
1983         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1984         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1985         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1986         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1987         expect_pending_htlcs_forwardable!(nodes[1]);
1988
1989         let ref payment_event_3 = expect_forward!(nodes[1]);
1990         assert_eq!(payment_event_3.msgs.len(), 2);
1991         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1992         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1993
1994         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1995         expect_pending_htlcs_forwardable!(nodes[2]);
1996
1997         let events = nodes[2].node.get_and_clear_pending_events();
1998         assert_eq!(events.len(), 2);
1999         match events[0] {
2000                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2001                         assert_eq!(our_payment_hash_21, *payment_hash);
2002                         assert_eq!(recv_value_21, amount_msat);
2003                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2004                         assert_eq!(via_channel_id, Some(chan_2.2));
2005                         match &purpose {
2006                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2007                                         assert!(payment_preimage.is_none());
2008                                         assert_eq!(our_payment_secret_21, *payment_secret);
2009                                 },
2010                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2011                         }
2012                 },
2013                 _ => panic!("Unexpected event"),
2014         }
2015         match events[1] {
2016                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2017                         assert_eq!(our_payment_hash_22, *payment_hash);
2018                         assert_eq!(recv_value_22, amount_msat);
2019                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2020                         assert_eq!(via_channel_id, Some(chan_2.2));
2021                         match &purpose {
2022                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2023                                         assert!(payment_preimage.is_none());
2024                                         assert_eq!(our_payment_secret_22, *payment_secret);
2025                                 },
2026                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2027                         }
2028                 },
2029                 _ => panic!("Unexpected event"),
2030         }
2031
2032         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2033         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2034         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2035
2036         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2037         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2038         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2039
2040         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2041         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);
2042         let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2043         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2044         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2045
2046         let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2047         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2048 }
2049
2050 #[test]
2051 fn channel_reserve_in_flight_removes() {
2052         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2053         // can send to its counterparty, but due to update ordering, the other side may not yet have
2054         // considered those HTLCs fully removed.
2055         // This tests that we don't count HTLCs which will not be included in the next remote
2056         // commitment transaction towards the reserve value (as it implies no commitment transaction
2057         // will be generated which violates the remote reserve value).
2058         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2059         // To test this we:
2060         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2061         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2062         //    you only consider the value of the first HTLC, it may not),
2063         //  * start routing a third HTLC from A to B,
2064         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2065         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2066         //  * deliver the first fulfill from B
2067         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2068         //    claim,
2069         //  * deliver A's response CS and RAA.
2070         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2071         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2072         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2073         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2074         let chanmon_cfgs = create_chanmon_cfgs(2);
2075         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2076         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2077         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2078         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2079
2080         let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2081         // Route the first two HTLCs.
2082         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2083         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2084         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2085
2086         // Start routing the third HTLC (this is just used to get everyone in the right state).
2087         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2088         let send_1 = {
2089                 nodes[0].node.send_payment_with_route(&route, payment_hash_3,
2090                         RecipientOnionFields::secret_only(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2091                 check_added_monitors!(nodes[0], 1);
2092                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2093                 assert_eq!(events.len(), 1);
2094                 SendEvent::from_event(events.remove(0))
2095         };
2096
2097         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2098         // initial fulfill/CS.
2099         nodes[1].node.claim_funds(payment_preimage_1);
2100         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2101         check_added_monitors!(nodes[1], 1);
2102         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2103
2104         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2105         // remove the second HTLC when we send the HTLC back from B to A.
2106         nodes[1].node.claim_funds(payment_preimage_2);
2107         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2108         check_added_monitors!(nodes[1], 1);
2109         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2110
2111         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2112         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2113         check_added_monitors!(nodes[0], 1);
2114         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2115         expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2116
2117         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2118         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2119         check_added_monitors!(nodes[1], 1);
2120         // B is already AwaitingRAA, so cant generate a CS here
2121         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2122
2123         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2124         check_added_monitors!(nodes[1], 1);
2125         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2126
2127         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2128         check_added_monitors!(nodes[0], 1);
2129         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2130
2131         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2132         check_added_monitors!(nodes[1], 1);
2133         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2134
2135         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2136         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2137         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2138         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2139         // on-chain as necessary).
2140         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2141         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2142         check_added_monitors!(nodes[0], 1);
2143         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2144         expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2145
2146         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2147         check_added_monitors!(nodes[1], 1);
2148         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2149
2150         expect_pending_htlcs_forwardable!(nodes[1]);
2151         expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2152
2153         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2154         // resolve the second HTLC from A's point of view.
2155         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2156         check_added_monitors!(nodes[0], 1);
2157         expect_payment_path_successful!(nodes[0]);
2158         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2159
2160         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2161         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2162         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2163         let send_2 = {
2164                 nodes[1].node.send_payment_with_route(&route, payment_hash_4,
2165                         RecipientOnionFields::secret_only(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2166                 check_added_monitors!(nodes[1], 1);
2167                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2168                 assert_eq!(events.len(), 1);
2169                 SendEvent::from_event(events.remove(0))
2170         };
2171
2172         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2173         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2174         check_added_monitors!(nodes[0], 1);
2175         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2176
2177         // Now just resolve all the outstanding messages/HTLCs for completeness...
2178
2179         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2180         check_added_monitors!(nodes[1], 1);
2181         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2182
2183         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2184         check_added_monitors!(nodes[1], 1);
2185
2186         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2187         check_added_monitors!(nodes[0], 1);
2188         expect_payment_path_successful!(nodes[0]);
2189         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2190
2191         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2192         check_added_monitors!(nodes[1], 1);
2193         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2194
2195         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2196         check_added_monitors!(nodes[0], 1);
2197
2198         expect_pending_htlcs_forwardable!(nodes[0]);
2199         expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2200
2201         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2202         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2203 }
2204
2205 #[test]
2206 fn channel_monitor_network_test() {
2207         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2208         // tests that ChannelMonitor is able to recover from various states.
2209         let chanmon_cfgs = create_chanmon_cfgs(5);
2210         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2211         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2212         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2213
2214         // Create some initial channels
2215         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2216         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2217         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2218         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2219
2220         // Make sure all nodes are at the same starting height
2221         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2222         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2223         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2224         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2225         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2226
2227         // Rebalance the network a bit by relaying one payment through all the channels...
2228         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2229         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2230         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2231         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2232
2233         // Simple case with no pending HTLCs:
2234         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2235         check_added_monitors!(nodes[1], 1);
2236         check_closed_broadcast!(nodes[1], true);
2237         {
2238                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2239                 assert_eq!(node_txn.len(), 1);
2240                 mine_transaction(&nodes[0], &node_txn[0]);
2241                 check_added_monitors!(nodes[0], 1);
2242                 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2243         }
2244         check_closed_broadcast!(nodes[0], true);
2245         assert_eq!(nodes[0].node.list_channels().len(), 0);
2246         assert_eq!(nodes[1].node.list_channels().len(), 1);
2247         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2248         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2249
2250         // One pending HTLC is discarded by the force-close:
2251         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2252
2253         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2254         // broadcasted until we reach the timelock time).
2255         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2256         check_closed_broadcast!(nodes[1], true);
2257         check_added_monitors!(nodes[1], 1);
2258         {
2259                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2260                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2261                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2262                 mine_transaction(&nodes[2], &node_txn[0]);
2263                 check_added_monitors!(nodes[2], 1);
2264                 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2265         }
2266         check_closed_broadcast!(nodes[2], true);
2267         assert_eq!(nodes[1].node.list_channels().len(), 0);
2268         assert_eq!(nodes[2].node.list_channels().len(), 1);
2269         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2270         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2271
2272         macro_rules! claim_funds {
2273                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2274                         {
2275                                 $node.node.claim_funds($preimage);
2276                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2277                                 check_added_monitors!($node, 1);
2278
2279                                 let events = $node.node.get_and_clear_pending_msg_events();
2280                                 assert_eq!(events.len(), 1);
2281                                 match events[0] {
2282                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2283                                                 assert!(update_add_htlcs.is_empty());
2284                                                 assert!(update_fail_htlcs.is_empty());
2285                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2286                                         },
2287                                         _ => panic!("Unexpected event"),
2288                                 };
2289                         }
2290                 }
2291         }
2292
2293         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2294         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2295         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2296         check_added_monitors!(nodes[2], 1);
2297         check_closed_broadcast!(nodes[2], true);
2298         let node2_commitment_txid;
2299         {
2300                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2301                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2302                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2303                 node2_commitment_txid = node_txn[0].txid();
2304
2305                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2306                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2307                 mine_transaction(&nodes[3], &node_txn[0]);
2308                 check_added_monitors!(nodes[3], 1);
2309                 check_preimage_claim(&nodes[3], &node_txn);
2310         }
2311         check_closed_broadcast!(nodes[3], true);
2312         assert_eq!(nodes[2].node.list_channels().len(), 0);
2313         assert_eq!(nodes[3].node.list_channels().len(), 1);
2314         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2315         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2316
2317         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2318         // confusing us in the following tests.
2319         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2320
2321         // One pending HTLC to time out:
2322         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2323         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2324         // buffer space).
2325
2326         let (close_chan_update_1, close_chan_update_2) = {
2327                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2328                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2329                 assert_eq!(events.len(), 2);
2330                 let close_chan_update_1 = match events[0] {
2331                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2332                                 msg.clone()
2333                         },
2334                         _ => panic!("Unexpected event"),
2335                 };
2336                 match events[1] {
2337                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2338                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2339                         },
2340                         _ => panic!("Unexpected event"),
2341                 }
2342                 check_added_monitors!(nodes[3], 1);
2343
2344                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2345                 {
2346                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2347                         node_txn.retain(|tx| {
2348                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2349                                         false
2350                                 } else { true }
2351                         });
2352                 }
2353
2354                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2355
2356                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2357                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2358
2359                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2360                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2361                 assert_eq!(events.len(), 2);
2362                 let close_chan_update_2 = match events[0] {
2363                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2364                                 msg.clone()
2365                         },
2366                         _ => panic!("Unexpected event"),
2367                 };
2368                 match events[1] {
2369                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2370                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2371                         },
2372                         _ => panic!("Unexpected event"),
2373                 }
2374                 check_added_monitors!(nodes[4], 1);
2375                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2376
2377                 mine_transaction(&nodes[4], &node_txn[0]);
2378                 check_preimage_claim(&nodes[4], &node_txn);
2379                 (close_chan_update_1, close_chan_update_2)
2380         };
2381         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2382         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2383         assert_eq!(nodes[3].node.list_channels().len(), 0);
2384         assert_eq!(nodes[4].node.list_channels().len(), 0);
2385
2386         assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2387                 ChannelMonitorUpdateStatus::Completed);
2388         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2389         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2390 }
2391
2392 #[test]
2393 fn test_justice_tx() {
2394         // Test justice txn built on revoked HTLC-Success tx, against both sides
2395         let mut alice_config = UserConfig::default();
2396         alice_config.channel_handshake_config.announced_channel = true;
2397         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2398         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2399         let mut bob_config = UserConfig::default();
2400         bob_config.channel_handshake_config.announced_channel = true;
2401         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2402         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2403         let user_cfgs = [Some(alice_config), Some(bob_config)];
2404         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2405         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2406         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2407         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2408         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2409         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2410         *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2411         // Create some new channels:
2412         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2413
2414         // A pending HTLC which will be revoked:
2415         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2416         // Get the will-be-revoked local txn from nodes[0]
2417         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2418         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2419         assert_eq!(revoked_local_txn[0].input.len(), 1);
2420         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2421         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2422         assert_eq!(revoked_local_txn[1].input.len(), 1);
2423         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2424         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2425         // Revoke the old state
2426         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2427
2428         {
2429                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2430                 {
2431                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2432                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2433                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2434
2435                         check_spends!(node_txn[0], revoked_local_txn[0]);
2436                         node_txn.swap_remove(0);
2437                 }
2438                 check_added_monitors!(nodes[1], 1);
2439                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2440                 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2441
2442                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2443                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2444                 // Verify broadcast of revoked HTLC-timeout
2445                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2446                 check_added_monitors!(nodes[0], 1);
2447                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2448                 // Broadcast revoked HTLC-timeout on node 1
2449                 mine_transaction(&nodes[1], &node_txn[1]);
2450                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2451         }
2452         get_announce_close_broadcast_events(&nodes, 0, 1);
2453
2454         assert_eq!(nodes[0].node.list_channels().len(), 0);
2455         assert_eq!(nodes[1].node.list_channels().len(), 0);
2456
2457         // We test justice_tx build by A on B's revoked HTLC-Success tx
2458         // Create some new channels:
2459         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2460         {
2461                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2462                 node_txn.clear();
2463         }
2464
2465         // A pending HTLC which will be revoked:
2466         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2467         // Get the will-be-revoked local txn from B
2468         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2469         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2470         assert_eq!(revoked_local_txn[0].input.len(), 1);
2471         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2472         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2473         // Revoke the old state
2474         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2475         {
2476                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2477                 {
2478                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2479                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2480                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2481
2482                         check_spends!(node_txn[0], revoked_local_txn[0]);
2483                         node_txn.swap_remove(0);
2484                 }
2485                 check_added_monitors!(nodes[0], 1);
2486                 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2487
2488                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2489                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2490                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2491                 check_added_monitors!(nodes[1], 1);
2492                 mine_transaction(&nodes[0], &node_txn[1]);
2493                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2494                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2495         }
2496         get_announce_close_broadcast_events(&nodes, 0, 1);
2497         assert_eq!(nodes[0].node.list_channels().len(), 0);
2498         assert_eq!(nodes[1].node.list_channels().len(), 0);
2499 }
2500
2501 #[test]
2502 fn revoked_output_claim() {
2503         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2504         // transaction is broadcast by its counterparty
2505         let chanmon_cfgs = create_chanmon_cfgs(2);
2506         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2507         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2508         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2509         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2510         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2511         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2512         assert_eq!(revoked_local_txn.len(), 1);
2513         // Only output is the full channel value back to nodes[0]:
2514         assert_eq!(revoked_local_txn[0].output.len(), 1);
2515         // Send a payment through, updating everyone's latest commitment txn
2516         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2517
2518         // Inform nodes[1] that nodes[0] broadcast a stale tx
2519         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2520         check_added_monitors!(nodes[1], 1);
2521         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2522         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2523         assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2524
2525         check_spends!(node_txn[0], revoked_local_txn[0]);
2526
2527         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2528         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2529         get_announce_close_broadcast_events(&nodes, 0, 1);
2530         check_added_monitors!(nodes[0], 1);
2531         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2532 }
2533
2534 #[test]
2535 fn claim_htlc_outputs_shared_tx() {
2536         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2537         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2538         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2539         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2540         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2541         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2542
2543         // Create some new channel:
2544         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2545
2546         // Rebalance the network to generate htlc in the two directions
2547         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2548         // 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
2549         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2550         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2551
2552         // Get the will-be-revoked local txn from node[0]
2553         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2554         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2555         assert_eq!(revoked_local_txn[0].input.len(), 1);
2556         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2557         assert_eq!(revoked_local_txn[1].input.len(), 1);
2558         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2559         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2560         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2561
2562         //Revoke the old state
2563         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2564
2565         {
2566                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2567                 check_added_monitors!(nodes[0], 1);
2568                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2569                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2570                 check_added_monitors!(nodes[1], 1);
2571                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2572                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2573                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2574
2575                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2576                 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2577
2578                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2579                 check_spends!(node_txn[0], revoked_local_txn[0]);
2580
2581                 let mut witness_lens = BTreeSet::new();
2582                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2583                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2584                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2585                 assert_eq!(witness_lens.len(), 3);
2586                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2587                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2588                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2589
2590                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2591                 // ANTI_REORG_DELAY confirmations.
2592                 mine_transaction(&nodes[1], &node_txn[0]);
2593                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2594                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2595         }
2596         get_announce_close_broadcast_events(&nodes, 0, 1);
2597         assert_eq!(nodes[0].node.list_channels().len(), 0);
2598         assert_eq!(nodes[1].node.list_channels().len(), 0);
2599 }
2600
2601 #[test]
2602 fn claim_htlc_outputs_single_tx() {
2603         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2604         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2605         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2606         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2607         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2608         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2609
2610         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2611
2612         // Rebalance the network to generate htlc in the two directions
2613         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2614         // 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
2615         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2616         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2617         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2618
2619         // Get the will-be-revoked local txn from node[0]
2620         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2621
2622         //Revoke the old state
2623         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2624
2625         {
2626                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2627                 check_added_monitors!(nodes[0], 1);
2628                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2629                 check_added_monitors!(nodes[1], 1);
2630                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2631                 let mut events = nodes[0].node.get_and_clear_pending_events();
2632                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2633                 match events.last().unwrap() {
2634                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2635                         _ => panic!("Unexpected event"),
2636                 }
2637
2638                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2639                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2640
2641                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2642                 assert_eq!(node_txn.len(), 7);
2643
2644                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2645                 assert_eq!(node_txn[0].input.len(), 1);
2646                 check_spends!(node_txn[0], chan_1.3);
2647                 assert_eq!(node_txn[1].input.len(), 1);
2648                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2649                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2650                 check_spends!(node_txn[1], node_txn[0]);
2651
2652                 // Justice transactions are indices 2-3-4
2653                 assert_eq!(node_txn[2].input.len(), 1);
2654                 assert_eq!(node_txn[3].input.len(), 1);
2655                 assert_eq!(node_txn[4].input.len(), 1);
2656
2657                 check_spends!(node_txn[2], revoked_local_txn[0]);
2658                 check_spends!(node_txn[3], revoked_local_txn[0]);
2659                 check_spends!(node_txn[4], revoked_local_txn[0]);
2660
2661                 let mut witness_lens = BTreeSet::new();
2662                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2663                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2664                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2665                 assert_eq!(witness_lens.len(), 3);
2666                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2667                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2668                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2669
2670                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2671                 // ANTI_REORG_DELAY confirmations.
2672                 mine_transaction(&nodes[1], &node_txn[2]);
2673                 mine_transaction(&nodes[1], &node_txn[3]);
2674                 mine_transaction(&nodes[1], &node_txn[4]);
2675                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2676                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2677         }
2678         get_announce_close_broadcast_events(&nodes, 0, 1);
2679         assert_eq!(nodes[0].node.list_channels().len(), 0);
2680         assert_eq!(nodes[1].node.list_channels().len(), 0);
2681 }
2682
2683 #[test]
2684 fn test_htlc_on_chain_success() {
2685         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2686         // the preimage backward accordingly. So here we test that ChannelManager is
2687         // broadcasting the right event to other nodes in payment path.
2688         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2689         // A --------------------> B ----------------------> C (preimage)
2690         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2691         // commitment transaction was broadcast.
2692         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2693         // towards B.
2694         // B should be able to claim via preimage if A then broadcasts its local tx.
2695         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2696         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2697         // PaymentSent event).
2698
2699         let chanmon_cfgs = create_chanmon_cfgs(3);
2700         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2701         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2702         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2703
2704         // Create some initial channels
2705         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2706         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2707
2708         // Ensure all nodes are at the same height
2709         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2710         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2711         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2712         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2713
2714         // Rebalance the network a bit by relaying one payment through all the channels...
2715         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2716         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2717
2718         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2719         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2720
2721         // Broadcast legit commitment tx from C on B's chain
2722         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2723         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2724         assert_eq!(commitment_tx.len(), 1);
2725         check_spends!(commitment_tx[0], chan_2.3);
2726         nodes[2].node.claim_funds(our_payment_preimage);
2727         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2728         nodes[2].node.claim_funds(our_payment_preimage_2);
2729         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2730         check_added_monitors!(nodes[2], 2);
2731         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2732         assert!(updates.update_add_htlcs.is_empty());
2733         assert!(updates.update_fail_htlcs.is_empty());
2734         assert!(updates.update_fail_malformed_htlcs.is_empty());
2735         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2736
2737         mine_transaction(&nodes[2], &commitment_tx[0]);
2738         check_closed_broadcast!(nodes[2], true);
2739         check_added_monitors!(nodes[2], 1);
2740         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2741         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2742         assert_eq!(node_txn.len(), 2);
2743         check_spends!(node_txn[0], commitment_tx[0]);
2744         check_spends!(node_txn[1], commitment_tx[0]);
2745         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2746         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2747         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2748         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2749         assert_eq!(node_txn[0].lock_time.0, 0);
2750         assert_eq!(node_txn[1].lock_time.0, 0);
2751
2752         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2753         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2754         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone(), node_txn[1].clone()]});
2755         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2756         {
2757                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2758                 assert_eq!(added_monitors.len(), 1);
2759                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2760                 added_monitors.clear();
2761         }
2762         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2763         assert_eq!(forwarded_events.len(), 3);
2764         match forwarded_events[0] {
2765                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2766                 _ => panic!("Unexpected event"),
2767         }
2768         let chan_id = Some(chan_1.2);
2769         match forwarded_events[1] {
2770                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2771                         assert_eq!(fee_earned_msat, Some(1000));
2772                         assert_eq!(prev_channel_id, chan_id);
2773                         assert_eq!(claim_from_onchain_tx, true);
2774                         assert_eq!(next_channel_id, Some(chan_2.2));
2775                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2776                 },
2777                 _ => panic!()
2778         }
2779         match forwarded_events[2] {
2780                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2781                         assert_eq!(fee_earned_msat, Some(1000));
2782                         assert_eq!(prev_channel_id, chan_id);
2783                         assert_eq!(claim_from_onchain_tx, true);
2784                         assert_eq!(next_channel_id, Some(chan_2.2));
2785                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2786                 },
2787                 _ => panic!()
2788         }
2789         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2790         {
2791                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2792                 assert_eq!(added_monitors.len(), 2);
2793                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2794                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2795                 added_monitors.clear();
2796         }
2797         assert_eq!(events.len(), 3);
2798
2799         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2800         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2801
2802         match nodes_2_event {
2803                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2804                 _ => panic!("Unexpected event"),
2805         }
2806
2807         match nodes_0_event {
2808                 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, .. } } => {
2809                         assert!(update_add_htlcs.is_empty());
2810                         assert!(update_fail_htlcs.is_empty());
2811                         assert_eq!(update_fulfill_htlcs.len(), 1);
2812                         assert!(update_fail_malformed_htlcs.is_empty());
2813                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2814                 },
2815                 _ => panic!("Unexpected event"),
2816         };
2817
2818         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2819         match events[0] {
2820                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2821                 _ => panic!("Unexpected event"),
2822         }
2823
2824         macro_rules! check_tx_local_broadcast {
2825                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2826                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2827                         assert_eq!(node_txn.len(), 2);
2828                         // Node[1]: 2 * HTLC-timeout tx
2829                         // Node[0]: 2 * HTLC-timeout tx
2830                         check_spends!(node_txn[0], $commitment_tx);
2831                         check_spends!(node_txn[1], $commitment_tx);
2832                         assert_ne!(node_txn[0].lock_time.0, 0);
2833                         assert_ne!(node_txn[1].lock_time.0, 0);
2834                         if $htlc_offered {
2835                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2836                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2837                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2838                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2839                         } else {
2840                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2841                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2842                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2843                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2844                         }
2845                         node_txn.clear();
2846                 } }
2847         }
2848         // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2849         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2850
2851         // Broadcast legit commitment tx from A on B's chain
2852         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2853         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2854         check_spends!(node_a_commitment_tx[0], chan_1.3);
2855         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2856         check_closed_broadcast!(nodes[1], true);
2857         check_added_monitors!(nodes[1], 1);
2858         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2859         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2860         assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2861         let commitment_spend =
2862                 if node_txn.len() == 1 {
2863                         &node_txn[0]
2864                 } else {
2865                         // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2866                         // FullBlockViaListen
2867                         if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2868                                 check_spends!(node_txn[1], commitment_tx[0]);
2869                                 check_spends!(node_txn[2], commitment_tx[0]);
2870                                 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2871                                 &node_txn[0]
2872                         } else {
2873                                 check_spends!(node_txn[0], commitment_tx[0]);
2874                                 check_spends!(node_txn[1], commitment_tx[0]);
2875                                 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2876                                 &node_txn[2]
2877                         }
2878                 };
2879
2880         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2881         assert_eq!(commitment_spend.input.len(), 2);
2882         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2883         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2884         assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1 + 1);
2885         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2886         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2887         // we already checked the same situation with A.
2888
2889         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2890         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2891         connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2892         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2893         check_closed_broadcast!(nodes[0], true);
2894         check_added_monitors!(nodes[0], 1);
2895         let events = nodes[0].node.get_and_clear_pending_events();
2896         assert_eq!(events.len(), 5);
2897         let mut first_claimed = false;
2898         for event in events {
2899                 match event {
2900                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2901                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2902                                         assert!(!first_claimed);
2903                                         first_claimed = true;
2904                                 } else {
2905                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2906                                         assert_eq!(payment_hash, payment_hash_2);
2907                                 }
2908                         },
2909                         Event::PaymentPathSuccessful { .. } => {},
2910                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2911                         _ => panic!("Unexpected event"),
2912                 }
2913         }
2914         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
2915 }
2916
2917 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2918         // Test that in case of a unilateral close onchain, we detect the state of output and
2919         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2920         // broadcasting the right event to other nodes in payment path.
2921         // A ------------------> B ----------------------> C (timeout)
2922         //    B's commitment tx                 C's commitment tx
2923         //            \                                  \
2924         //         B's HTLC timeout tx               B's timeout tx
2925
2926         let chanmon_cfgs = create_chanmon_cfgs(3);
2927         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2928         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2929         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2930         *nodes[0].connect_style.borrow_mut() = connect_style;
2931         *nodes[1].connect_style.borrow_mut() = connect_style;
2932         *nodes[2].connect_style.borrow_mut() = connect_style;
2933
2934         // Create some intial channels
2935         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2936         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2937
2938         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2939         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2940         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2941
2942         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2943
2944         // Broadcast legit commitment tx from C on B's chain
2945         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2946         check_spends!(commitment_tx[0], chan_2.3);
2947         nodes[2].node.fail_htlc_backwards(&payment_hash);
2948         check_added_monitors!(nodes[2], 0);
2949         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2950         check_added_monitors!(nodes[2], 1);
2951
2952         let events = nodes[2].node.get_and_clear_pending_msg_events();
2953         assert_eq!(events.len(), 1);
2954         match events[0] {
2955                 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, .. } } => {
2956                         assert!(update_add_htlcs.is_empty());
2957                         assert!(!update_fail_htlcs.is_empty());
2958                         assert!(update_fulfill_htlcs.is_empty());
2959                         assert!(update_fail_malformed_htlcs.is_empty());
2960                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2961                 },
2962                 _ => panic!("Unexpected event"),
2963         };
2964         mine_transaction(&nodes[2], &commitment_tx[0]);
2965         check_closed_broadcast!(nodes[2], true);
2966         check_added_monitors!(nodes[2], 1);
2967         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2968         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2969         assert_eq!(node_txn.len(), 0);
2970
2971         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2972         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2973         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2974         mine_transaction(&nodes[1], &commitment_tx[0]);
2975         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2976         let timeout_tx;
2977         {
2978                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2979                 assert_eq!(node_txn.len(), 3); // 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2980
2981                 check_spends!(node_txn[2], commitment_tx[0]);
2982                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2983
2984                 check_spends!(node_txn[0], chan_2.3);
2985                 check_spends!(node_txn[1], node_txn[0]);
2986                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2987                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2988
2989                 timeout_tx = node_txn[2].clone();
2990                 node_txn.clear();
2991         }
2992
2993         mine_transaction(&nodes[1], &timeout_tx);
2994         check_added_monitors!(nodes[1], 1);
2995         check_closed_broadcast!(nodes[1], true);
2996
2997         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2998
2999         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 }]);
3000         check_added_monitors!(nodes[1], 1);
3001         let events = nodes[1].node.get_and_clear_pending_msg_events();
3002         assert_eq!(events.len(), 1);
3003         match events[0] {
3004                 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, .. } } => {
3005                         assert!(update_add_htlcs.is_empty());
3006                         assert!(!update_fail_htlcs.is_empty());
3007                         assert!(update_fulfill_htlcs.is_empty());
3008                         assert!(update_fail_malformed_htlcs.is_empty());
3009                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3010                 },
3011                 _ => panic!("Unexpected event"),
3012         };
3013
3014         // Broadcast legit commitment tx from B on A's chain
3015         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3016         check_spends!(commitment_tx[0], chan_1.3);
3017
3018         mine_transaction(&nodes[0], &commitment_tx[0]);
3019         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
3020
3021         check_closed_broadcast!(nodes[0], true);
3022         check_added_monitors!(nodes[0], 1);
3023         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
3024         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
3025         assert_eq!(node_txn.len(), 1);
3026         check_spends!(node_txn[0], commitment_tx[0]);
3027         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3028 }
3029
3030 #[test]
3031 fn test_htlc_on_chain_timeout() {
3032         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3033         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3034         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3035 }
3036
3037 #[test]
3038 fn test_simple_commitment_revoked_fail_backward() {
3039         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3040         // and fail backward accordingly.
3041
3042         let chanmon_cfgs = create_chanmon_cfgs(3);
3043         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3044         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3045         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3046
3047         // Create some initial channels
3048         create_announced_chan_between_nodes(&nodes, 0, 1);
3049         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3050
3051         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3052         // Get the will-be-revoked local txn from nodes[2]
3053         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3054         // Revoke the old state
3055         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3056
3057         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3058
3059         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3060         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3061         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3062         check_added_monitors!(nodes[1], 1);
3063         check_closed_broadcast!(nodes[1], true);
3064
3065         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 }]);
3066         check_added_monitors!(nodes[1], 1);
3067         let events = nodes[1].node.get_and_clear_pending_msg_events();
3068         assert_eq!(events.len(), 1);
3069         match events[0] {
3070                 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, .. } } => {
3071                         assert!(update_add_htlcs.is_empty());
3072                         assert_eq!(update_fail_htlcs.len(), 1);
3073                         assert!(update_fulfill_htlcs.is_empty());
3074                         assert!(update_fail_malformed_htlcs.is_empty());
3075                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3076
3077                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3078                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3079                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3080                 },
3081                 _ => panic!("Unexpected event"),
3082         }
3083 }
3084
3085 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3086         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3087         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3088         // commitment transaction anymore.
3089         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3090         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3091         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3092         // technically disallowed and we should probably handle it reasonably.
3093         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3094         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3095         // transactions:
3096         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3097         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3098         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3099         //   and once they revoke the previous commitment transaction (allowing us to send a new
3100         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3101         let chanmon_cfgs = create_chanmon_cfgs(3);
3102         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3103         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3104         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3105
3106         // Create some initial channels
3107         create_announced_chan_between_nodes(&nodes, 0, 1);
3108         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3109
3110         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 });
3111         // Get the will-be-revoked local txn from nodes[2]
3112         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3113         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3114         // Revoke the old state
3115         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3116
3117         let value = if use_dust {
3118                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3119                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3120                 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3121                         .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3122         } else { 3000000 };
3123
3124         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3125         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3126         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3127
3128         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3129         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3130         check_added_monitors!(nodes[2], 1);
3131         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3132         assert!(updates.update_add_htlcs.is_empty());
3133         assert!(updates.update_fulfill_htlcs.is_empty());
3134         assert!(updates.update_fail_malformed_htlcs.is_empty());
3135         assert_eq!(updates.update_fail_htlcs.len(), 1);
3136         assert!(updates.update_fee.is_none());
3137         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3138         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3139         // Drop the last RAA from 3 -> 2
3140
3141         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3142         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3143         check_added_monitors!(nodes[2], 1);
3144         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3145         assert!(updates.update_add_htlcs.is_empty());
3146         assert!(updates.update_fulfill_htlcs.is_empty());
3147         assert!(updates.update_fail_malformed_htlcs.is_empty());
3148         assert_eq!(updates.update_fail_htlcs.len(), 1);
3149         assert!(updates.update_fee.is_none());
3150         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3151         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3152         check_added_monitors!(nodes[1], 1);
3153         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3154         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3155         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3156         check_added_monitors!(nodes[2], 1);
3157
3158         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3159         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3160         check_added_monitors!(nodes[2], 1);
3161         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3162         assert!(updates.update_add_htlcs.is_empty());
3163         assert!(updates.update_fulfill_htlcs.is_empty());
3164         assert!(updates.update_fail_malformed_htlcs.is_empty());
3165         assert_eq!(updates.update_fail_htlcs.len(), 1);
3166         assert!(updates.update_fee.is_none());
3167         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3168         // At this point first_payment_hash has dropped out of the latest two commitment
3169         // transactions that nodes[1] is tracking...
3170         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3171         check_added_monitors!(nodes[1], 1);
3172         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3173         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3174         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3175         check_added_monitors!(nodes[2], 1);
3176
3177         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3178         // on nodes[2]'s RAA.
3179         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3180         nodes[1].node.send_payment_with_route(&route, fourth_payment_hash,
3181                 RecipientOnionFields::secret_only(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3182         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3183         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3184         check_added_monitors!(nodes[1], 0);
3185
3186         if deliver_bs_raa {
3187                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3188                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3189                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3190                 check_added_monitors!(nodes[1], 1);
3191                 let events = nodes[1].node.get_and_clear_pending_events();
3192                 assert_eq!(events.len(), 2);
3193                 match events[0] {
3194                         Event::PendingHTLCsForwardable { .. } => { },
3195                         _ => panic!("Unexpected event"),
3196                 };
3197                 match events[1] {
3198                         Event::HTLCHandlingFailed { .. } => { },
3199                         _ => panic!("Unexpected event"),
3200                 }
3201                 // Deliberately don't process the pending fail-back so they all fail back at once after
3202                 // block connection just like the !deliver_bs_raa case
3203         }
3204
3205         let mut failed_htlcs = HashSet::new();
3206         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3207
3208         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3209         check_added_monitors!(nodes[1], 1);
3210         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3211
3212         let events = nodes[1].node.get_and_clear_pending_events();
3213         assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3214         match events[0] {
3215                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3216                 _ => panic!("Unexepected event"),
3217         }
3218         match events[1] {
3219                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3220                         assert_eq!(*payment_hash, fourth_payment_hash);
3221                 },
3222                 _ => panic!("Unexpected event"),
3223         }
3224         match events[2] {
3225                 Event::PaymentFailed { ref payment_hash, .. } => {
3226                         assert_eq!(*payment_hash, fourth_payment_hash);
3227                 },
3228                 _ => panic!("Unexpected event"),
3229         }
3230
3231         nodes[1].node.process_pending_htlc_forwards();
3232         check_added_monitors!(nodes[1], 1);
3233
3234         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3235         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3236
3237         if deliver_bs_raa {
3238                 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3239                 match nodes_2_event {
3240                         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, .. } } => {
3241                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3242                                 assert_eq!(update_add_htlcs.len(), 1);
3243                                 assert!(update_fulfill_htlcs.is_empty());
3244                                 assert!(update_fail_htlcs.is_empty());
3245                                 assert!(update_fail_malformed_htlcs.is_empty());
3246                         },
3247                         _ => panic!("Unexpected event"),
3248                 }
3249         }
3250
3251         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3252         match nodes_2_event {
3253                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3254                         assert_eq!(channel_id, chan_2.2);
3255                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3256                 },
3257                 _ => panic!("Unexpected event"),
3258         }
3259
3260         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3261         match nodes_0_event {
3262                 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, .. } } => {
3263                         assert!(update_add_htlcs.is_empty());
3264                         assert_eq!(update_fail_htlcs.len(), 3);
3265                         assert!(update_fulfill_htlcs.is_empty());
3266                         assert!(update_fail_malformed_htlcs.is_empty());
3267                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3268
3269                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3270                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3271                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3272
3273                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3274
3275                         let events = nodes[0].node.get_and_clear_pending_events();
3276                         assert_eq!(events.len(), 6);
3277                         match events[0] {
3278                                 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3279                                         assert!(failed_htlcs.insert(payment_hash.0));
3280                                         // If we delivered B's RAA we got an unknown preimage error, not something
3281                                         // that we should update our routing table for.
3282                                         if !deliver_bs_raa {
3283                                                 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3284                                         }
3285                                 },
3286                                 _ => panic!("Unexpected event"),
3287                         }
3288                         match events[1] {
3289                                 Event::PaymentFailed { ref payment_hash, .. } => {
3290                                         assert_eq!(*payment_hash, first_payment_hash);
3291                                 },
3292                                 _ => panic!("Unexpected event"),
3293                         }
3294                         match events[2] {
3295                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3296                                         assert!(failed_htlcs.insert(payment_hash.0));
3297                                 },
3298                                 _ => panic!("Unexpected event"),
3299                         }
3300                         match events[3] {
3301                                 Event::PaymentFailed { ref payment_hash, .. } => {
3302                                         assert_eq!(*payment_hash, second_payment_hash);
3303                                 },
3304                                 _ => panic!("Unexpected event"),
3305                         }
3306                         match events[4] {
3307                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3308                                         assert!(failed_htlcs.insert(payment_hash.0));
3309                                 },
3310                                 _ => panic!("Unexpected event"),
3311                         }
3312                         match events[5] {
3313                                 Event::PaymentFailed { ref payment_hash, .. } => {
3314                                         assert_eq!(*payment_hash, third_payment_hash);
3315                                 },
3316                                 _ => panic!("Unexpected event"),
3317                         }
3318                 },
3319                 _ => panic!("Unexpected event"),
3320         }
3321
3322         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3323         match events[0] {
3324                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3325                 _ => panic!("Unexpected event"),
3326         }
3327
3328         assert!(failed_htlcs.contains(&first_payment_hash.0));
3329         assert!(failed_htlcs.contains(&second_payment_hash.0));
3330         assert!(failed_htlcs.contains(&third_payment_hash.0));
3331 }
3332
3333 #[test]
3334 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3335         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3336         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3337         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3338         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3339 }
3340
3341 #[test]
3342 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3343         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3344         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3345         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3346         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3347 }
3348
3349 #[test]
3350 fn fail_backward_pending_htlc_upon_channel_failure() {
3351         let chanmon_cfgs = create_chanmon_cfgs(2);
3352         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3353         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3354         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3355         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3356
3357         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3358         {
3359                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3360                 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret),
3361                         PaymentId(payment_hash.0)).unwrap();
3362                 check_added_monitors!(nodes[0], 1);
3363
3364                 let payment_event = {
3365                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3366                         assert_eq!(events.len(), 1);
3367                         SendEvent::from_event(events.remove(0))
3368                 };
3369                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3370                 assert_eq!(payment_event.msgs.len(), 1);
3371         }
3372
3373         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3374         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3375         {
3376                 nodes[0].node.send_payment_with_route(&route, failed_payment_hash,
3377                         RecipientOnionFields::secret_only(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3378                 check_added_monitors!(nodes[0], 0);
3379
3380                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3381         }
3382
3383         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3384         {
3385                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3386
3387                 let secp_ctx = Secp256k1::new();
3388                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3389                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3390                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(
3391                         &route.paths[0], 50_000, RecipientOnionFields::secret_only(payment_secret), current_height, &None).unwrap();
3392                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3393                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3394
3395                 // Send a 0-msat update_add_htlc to fail the channel.
3396                 let update_add_htlc = msgs::UpdateAddHTLC {
3397                         channel_id: chan.2,
3398                         htlc_id: 0,
3399                         amount_msat: 0,
3400                         payment_hash,
3401                         cltv_expiry,
3402                         onion_routing_packet,
3403                 };
3404                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3405         }
3406         let events = nodes[0].node.get_and_clear_pending_events();
3407         assert_eq!(events.len(), 3);
3408         // Check that Alice fails backward the pending HTLC from the second payment.
3409         match events[0] {
3410                 Event::PaymentPathFailed { payment_hash, .. } => {
3411                         assert_eq!(payment_hash, failed_payment_hash);
3412                 },
3413                 _ => panic!("Unexpected event"),
3414         }
3415         match events[1] {
3416                 Event::PaymentFailed { payment_hash, .. } => {
3417                         assert_eq!(payment_hash, failed_payment_hash);
3418                 },
3419                 _ => panic!("Unexpected event"),
3420         }
3421         match events[2] {
3422                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3423                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3424                 },
3425                 _ => panic!("Unexpected event {:?}", events[1]),
3426         }
3427         check_closed_broadcast!(nodes[0], true);
3428         check_added_monitors!(nodes[0], 1);
3429 }
3430
3431 #[test]
3432 fn test_htlc_ignore_latest_remote_commitment() {
3433         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3434         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3435         let chanmon_cfgs = create_chanmon_cfgs(2);
3436         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3437         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3438         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3439         if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3440                 // We rely on the ability to connect a block redundantly, which isn't allowed via
3441                 // `chain::Listen`, so we never run the test if we randomly get assigned that
3442                 // connect_style.
3443                 return;
3444         }
3445         create_announced_chan_between_nodes(&nodes, 0, 1);
3446
3447         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3448         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3449         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3450         check_closed_broadcast!(nodes[0], true);
3451         check_added_monitors!(nodes[0], 1);
3452         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3453
3454         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3455         assert_eq!(node_txn.len(), 3);
3456         assert_eq!(node_txn[0], node_txn[1]);
3457
3458         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
3459         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3460         check_closed_broadcast!(nodes[1], true);
3461         check_added_monitors!(nodes[1], 1);
3462         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3463
3464         // Duplicate the connect_block call since this may happen due to other listeners
3465         // registering new transactions
3466         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3467 }
3468
3469 #[test]
3470 fn test_force_close_fail_back() {
3471         // Check which HTLCs are failed-backwards on channel force-closure
3472         let chanmon_cfgs = create_chanmon_cfgs(3);
3473         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3474         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3475         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3476         create_announced_chan_between_nodes(&nodes, 0, 1);
3477         create_announced_chan_between_nodes(&nodes, 1, 2);
3478
3479         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3480
3481         let mut payment_event = {
3482                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3483                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3484                 check_added_monitors!(nodes[0], 1);
3485
3486                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3487                 assert_eq!(events.len(), 1);
3488                 SendEvent::from_event(events.remove(0))
3489         };
3490
3491         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3492         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3493
3494         expect_pending_htlcs_forwardable!(nodes[1]);
3495
3496         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3497         assert_eq!(events_2.len(), 1);
3498         payment_event = SendEvent::from_event(events_2.remove(0));
3499         assert_eq!(payment_event.msgs.len(), 1);
3500
3501         check_added_monitors!(nodes[1], 1);
3502         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3503         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3504         check_added_monitors!(nodes[2], 1);
3505         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3506
3507         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3508         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3509         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3510
3511         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3512         check_closed_broadcast!(nodes[2], true);
3513         check_added_monitors!(nodes[2], 1);
3514         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3515         let tx = {
3516                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3517                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3518                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3519                 // back to nodes[1] upon timeout otherwise.
3520                 assert_eq!(node_txn.len(), 1);
3521                 node_txn.remove(0)
3522         };
3523
3524         mine_transaction(&nodes[1], &tx);
3525
3526         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3527         check_closed_broadcast!(nodes[1], true);
3528         check_added_monitors!(nodes[1], 1);
3529         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3530
3531         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3532         {
3533                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3534                         .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);
3535         }
3536         mine_transaction(&nodes[2], &tx);
3537         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3538         assert_eq!(node_txn.len(), 1);
3539         assert_eq!(node_txn[0].input.len(), 1);
3540         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3541         assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3542         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3543
3544         check_spends!(node_txn[0], tx);
3545 }
3546
3547 #[test]
3548 fn test_dup_events_on_peer_disconnect() {
3549         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3550         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3551         // as we used to generate the event immediately upon receipt of the payment preimage in the
3552         // update_fulfill_htlc message.
3553
3554         let chanmon_cfgs = create_chanmon_cfgs(2);
3555         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3556         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3557         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3558         create_announced_chan_between_nodes(&nodes, 0, 1);
3559
3560         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3561
3562         nodes[1].node.claim_funds(payment_preimage);
3563         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3564         check_added_monitors!(nodes[1], 1);
3565         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3566         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3567         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3568
3569         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3570         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3571
3572         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3573         expect_payment_path_successful!(nodes[0]);
3574 }
3575
3576 #[test]
3577 fn test_peer_disconnected_before_funding_broadcasted() {
3578         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3579         // before the funding transaction has been broadcasted.
3580         let chanmon_cfgs = create_chanmon_cfgs(2);
3581         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3582         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3583         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3584
3585         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3586         // broadcasted, even though it's created by `nodes[0]`.
3587         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();
3588         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3589         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3590         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3591         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3592
3593         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3594         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3595
3596         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3597
3598         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3599         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3600
3601         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3602         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3603         // broadcasted.
3604         {
3605                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3606         }
3607
3608         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3609         // disconnected before the funding transaction was broadcasted.
3610         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3611         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3612
3613         check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3614         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3615 }
3616
3617 #[test]
3618 fn test_simple_peer_disconnect() {
3619         // Test that we can reconnect when there are no lost messages
3620         let chanmon_cfgs = create_chanmon_cfgs(3);
3621         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3622         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3623         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3624         create_announced_chan_between_nodes(&nodes, 0, 1);
3625         create_announced_chan_between_nodes(&nodes, 1, 2);
3626
3627         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3628         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3629         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3630
3631         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3632         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3633         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3634         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3635
3636         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3637         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3638         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3639
3640         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3641         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3642         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3643         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3644
3645         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3646         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3647
3648         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3649         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3650
3651         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3652         {
3653                 let events = nodes[0].node.get_and_clear_pending_events();
3654                 assert_eq!(events.len(), 4);
3655                 match events[0] {
3656                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3657                                 assert_eq!(payment_preimage, payment_preimage_3);
3658                                 assert_eq!(payment_hash, payment_hash_3);
3659                         },
3660                         _ => panic!("Unexpected event"),
3661                 }
3662                 match events[1] {
3663                         Event::PaymentPathSuccessful { .. } => {},
3664                         _ => panic!("Unexpected event"),
3665                 }
3666                 match events[2] {
3667                         Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3668                                 assert_eq!(payment_hash, payment_hash_5);
3669                                 assert!(payment_failed_permanently);
3670                         },
3671                         _ => panic!("Unexpected event"),
3672                 }
3673                 match events[3] {
3674                         Event::PaymentFailed { payment_hash, .. } => {
3675                                 assert_eq!(payment_hash, payment_hash_5);
3676                         },
3677                         _ => panic!("Unexpected event"),
3678                 }
3679         }
3680
3681         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3682         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3683 }
3684
3685 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3686         // Test that we can reconnect when in-flight HTLC updates get dropped
3687         let chanmon_cfgs = create_chanmon_cfgs(2);
3688         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3689         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3690         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3691
3692         let mut as_channel_ready = None;
3693         let channel_id = if messages_delivered == 0 {
3694                 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3695                 as_channel_ready = Some(channel_ready);
3696                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3697                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3698                 // it before the channel_reestablish message.
3699                 chan_id
3700         } else {
3701                 create_announced_chan_between_nodes(&nodes, 0, 1).2
3702         };
3703
3704         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3705
3706         let payment_event = {
3707                 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3708                         RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3709                 check_added_monitors!(nodes[0], 1);
3710
3711                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3712                 assert_eq!(events.len(), 1);
3713                 SendEvent::from_event(events.remove(0))
3714         };
3715         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3716
3717         if messages_delivered < 2 {
3718                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3719         } else {
3720                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3721                 if messages_delivered >= 3 {
3722                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3723                         check_added_monitors!(nodes[1], 1);
3724                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3725
3726                         if messages_delivered >= 4 {
3727                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3728                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3729                                 check_added_monitors!(nodes[0], 1);
3730
3731                                 if messages_delivered >= 5 {
3732                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3733                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3734                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3735                                         check_added_monitors!(nodes[0], 1);
3736
3737                                         if messages_delivered >= 6 {
3738                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3739                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3740                                                 check_added_monitors!(nodes[1], 1);
3741                                         }
3742                                 }
3743                         }
3744                 }
3745         }
3746
3747         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3748         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3749         if messages_delivered < 3 {
3750                 if simulate_broken_lnd {
3751                         // lnd has a long-standing bug where they send a channel_ready prior to a
3752                         // channel_reestablish if you reconnect prior to channel_ready time.
3753                         //
3754                         // Here we simulate that behavior, delivering a channel_ready immediately on
3755                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3756                         // in `reconnect_nodes` but we currently don't fail based on that.
3757                         //
3758                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3759                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3760                 }
3761                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3762                 // received on either side, both sides will need to resend them.
3763                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3764         } else if messages_delivered == 3 {
3765                 // nodes[0] still wants its RAA + commitment_signed
3766                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3767         } else if messages_delivered == 4 {
3768                 // nodes[0] still wants its commitment_signed
3769                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3770         } else if messages_delivered == 5 {
3771                 // nodes[1] still wants its final RAA
3772                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3773         } else if messages_delivered == 6 {
3774                 // Everything was delivered...
3775                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3776         }
3777
3778         let events_1 = nodes[1].node.get_and_clear_pending_events();
3779         if messages_delivered == 0 {
3780                 assert_eq!(events_1.len(), 2);
3781                 match events_1[0] {
3782                         Event::ChannelReady { .. } => { },
3783                         _ => panic!("Unexpected event"),
3784                 };
3785                 match events_1[1] {
3786                         Event::PendingHTLCsForwardable { .. } => { },
3787                         _ => panic!("Unexpected event"),
3788                 };
3789         } else {
3790                 assert_eq!(events_1.len(), 1);
3791                 match events_1[0] {
3792                         Event::PendingHTLCsForwardable { .. } => { },
3793                         _ => panic!("Unexpected event"),
3794                 };
3795         }
3796
3797         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3798         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3799         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3800
3801         nodes[1].node.process_pending_htlc_forwards();
3802
3803         let events_2 = nodes[1].node.get_and_clear_pending_events();
3804         assert_eq!(events_2.len(), 1);
3805         match events_2[0] {
3806                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3807                         assert_eq!(payment_hash_1, *payment_hash);
3808                         assert_eq!(amount_msat, 1_000_000);
3809                         assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3810                         assert_eq!(via_channel_id, Some(channel_id));
3811                         match &purpose {
3812                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3813                                         assert!(payment_preimage.is_none());
3814                                         assert_eq!(payment_secret_1, *payment_secret);
3815                                 },
3816                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3817                         }
3818                 },
3819                 _ => panic!("Unexpected event"),
3820         }
3821
3822         nodes[1].node.claim_funds(payment_preimage_1);
3823         check_added_monitors!(nodes[1], 1);
3824         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3825
3826         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3827         assert_eq!(events_3.len(), 1);
3828         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3829                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3830                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3831                         assert!(updates.update_add_htlcs.is_empty());
3832                         assert!(updates.update_fail_htlcs.is_empty());
3833                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3834                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3835                         assert!(updates.update_fee.is_none());
3836                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3837                 },
3838                 _ => panic!("Unexpected event"),
3839         };
3840
3841         if messages_delivered >= 1 {
3842                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3843
3844                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3845                 assert_eq!(events_4.len(), 1);
3846                 match events_4[0] {
3847                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3848                                 assert_eq!(payment_preimage_1, *payment_preimage);
3849                                 assert_eq!(payment_hash_1, *payment_hash);
3850                         },
3851                         _ => panic!("Unexpected event"),
3852                 }
3853
3854                 if messages_delivered >= 2 {
3855                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3856                         check_added_monitors!(nodes[0], 1);
3857                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3858
3859                         if messages_delivered >= 3 {
3860                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3861                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3862                                 check_added_monitors!(nodes[1], 1);
3863
3864                                 if messages_delivered >= 4 {
3865                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3866                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3867                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3868                                         check_added_monitors!(nodes[1], 1);
3869
3870                                         if messages_delivered >= 5 {
3871                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3872                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3873                                                 check_added_monitors!(nodes[0], 1);
3874                                         }
3875                                 }
3876                         }
3877                 }
3878         }
3879
3880         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3881         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3882         if messages_delivered < 2 {
3883                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3884                 if messages_delivered < 1 {
3885                         expect_payment_sent!(nodes[0], payment_preimage_1);
3886                 } else {
3887                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3888                 }
3889         } else if messages_delivered == 2 {
3890                 // nodes[0] still wants its RAA + commitment_signed
3891                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3892         } else if messages_delivered == 3 {
3893                 // nodes[0] still wants its commitment_signed
3894                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3895         } else if messages_delivered == 4 {
3896                 // nodes[1] still wants its final RAA
3897                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3898         } else if messages_delivered == 5 {
3899                 // Everything was delivered...
3900                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3901         }
3902
3903         if messages_delivered == 1 || messages_delivered == 2 {
3904                 expect_payment_path_successful!(nodes[0]);
3905         }
3906         if messages_delivered <= 5 {
3907                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3908                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3909         }
3910         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3911
3912         if messages_delivered > 2 {
3913                 expect_payment_path_successful!(nodes[0]);
3914         }
3915
3916         // Channel should still work fine...
3917         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3918         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3919         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3920 }
3921
3922 #[test]
3923 fn test_drop_messages_peer_disconnect_a() {
3924         do_test_drop_messages_peer_disconnect(0, true);
3925         do_test_drop_messages_peer_disconnect(0, false);
3926         do_test_drop_messages_peer_disconnect(1, false);
3927         do_test_drop_messages_peer_disconnect(2, false);
3928 }
3929
3930 #[test]
3931 fn test_drop_messages_peer_disconnect_b() {
3932         do_test_drop_messages_peer_disconnect(3, false);
3933         do_test_drop_messages_peer_disconnect(4, false);
3934         do_test_drop_messages_peer_disconnect(5, false);
3935         do_test_drop_messages_peer_disconnect(6, false);
3936 }
3937
3938 #[test]
3939 fn test_channel_ready_without_best_block_updated() {
3940         // Previously, if we were offline when a funding transaction was locked in, and then we came
3941         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3942         // generate a channel_ready until a later best_block_updated. This tests that we generate the
3943         // channel_ready immediately instead.
3944         let chanmon_cfgs = create_chanmon_cfgs(2);
3945         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3946         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3947         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3948         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3949
3950         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
3951
3952         let conf_height = nodes[0].best_block_info().1 + 1;
3953         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3954         let block_txn = [funding_tx];
3955         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3956         let conf_block_header = nodes[0].get_block_header(conf_height);
3957         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3958
3959         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
3960         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
3961         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3962 }
3963
3964 #[test]
3965 fn test_drop_messages_peer_disconnect_dual_htlc() {
3966         // Test that we can handle reconnecting when both sides of a channel have pending
3967         // commitment_updates when we disconnect.
3968         let chanmon_cfgs = create_chanmon_cfgs(2);
3969         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3970         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3971         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3972         create_announced_chan_between_nodes(&nodes, 0, 1);
3973
3974         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3975
3976         // Now try to send a second payment which will fail to send
3977         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3978         nodes[0].node.send_payment_with_route(&route, payment_hash_2,
3979                 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
3980         check_added_monitors!(nodes[0], 1);
3981
3982         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3983         assert_eq!(events_1.len(), 1);
3984         match events_1[0] {
3985                 MessageSendEvent::UpdateHTLCs { .. } => {},
3986                 _ => panic!("Unexpected event"),
3987         }
3988
3989         nodes[1].node.claim_funds(payment_preimage_1);
3990         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3991         check_added_monitors!(nodes[1], 1);
3992
3993         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3994         assert_eq!(events_2.len(), 1);
3995         match events_2[0] {
3996                 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 } } => {
3997                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3998                         assert!(update_add_htlcs.is_empty());
3999                         assert_eq!(update_fulfill_htlcs.len(), 1);
4000                         assert!(update_fail_htlcs.is_empty());
4001                         assert!(update_fail_malformed_htlcs.is_empty());
4002                         assert!(update_fee.is_none());
4003
4004                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4005                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4006                         assert_eq!(events_3.len(), 1);
4007                         match events_3[0] {
4008                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4009                                         assert_eq!(*payment_preimage, payment_preimage_1);
4010                                         assert_eq!(*payment_hash, payment_hash_1);
4011                                 },
4012                                 _ => panic!("Unexpected event"),
4013                         }
4014
4015                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4016                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4017                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4018                         check_added_monitors!(nodes[0], 1);
4019                 },
4020                 _ => panic!("Unexpected event"),
4021         }
4022
4023         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4024         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4025
4026         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();
4027         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4028         assert_eq!(reestablish_1.len(), 1);
4029         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();
4030         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4031         assert_eq!(reestablish_2.len(), 1);
4032
4033         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4034         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4035         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4036         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4037
4038         assert!(as_resp.0.is_none());
4039         assert!(bs_resp.0.is_none());
4040
4041         assert!(bs_resp.1.is_none());
4042         assert!(bs_resp.2.is_none());
4043
4044         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4045
4046         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4047         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4048         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4049         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4050         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4051         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4052         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4053         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4054         // No commitment_signed so get_event_msg's assert(len == 1) passes
4055         check_added_monitors!(nodes[1], 1);
4056
4057         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4058         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4059         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4060         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4061         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4062         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4063         assert!(bs_second_commitment_signed.update_fee.is_none());
4064         check_added_monitors!(nodes[1], 1);
4065
4066         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4067         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4068         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4069         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4070         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4071         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4072         assert!(as_commitment_signed.update_fee.is_none());
4073         check_added_monitors!(nodes[0], 1);
4074
4075         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4076         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4077         // No commitment_signed so get_event_msg's assert(len == 1) passes
4078         check_added_monitors!(nodes[0], 1);
4079
4080         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4081         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4082         // No commitment_signed so get_event_msg's assert(len == 1) passes
4083         check_added_monitors!(nodes[1], 1);
4084
4085         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4086         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4087         check_added_monitors!(nodes[1], 1);
4088
4089         expect_pending_htlcs_forwardable!(nodes[1]);
4090
4091         let events_5 = nodes[1].node.get_and_clear_pending_events();
4092         assert_eq!(events_5.len(), 1);
4093         match events_5[0] {
4094                 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4095                         assert_eq!(payment_hash_2, *payment_hash);
4096                         match &purpose {
4097                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4098                                         assert!(payment_preimage.is_none());
4099                                         assert_eq!(payment_secret_2, *payment_secret);
4100                                 },
4101                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4102                         }
4103                 },
4104                 _ => panic!("Unexpected event"),
4105         }
4106
4107         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4108         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4109         check_added_monitors!(nodes[0], 1);
4110
4111         expect_payment_path_successful!(nodes[0]);
4112         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4113 }
4114
4115 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4116         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4117         // to avoid our counterparty failing the channel.
4118         let chanmon_cfgs = create_chanmon_cfgs(2);
4119         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4120         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4121         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4122
4123         create_announced_chan_between_nodes(&nodes, 0, 1);
4124
4125         let our_payment_hash = if send_partial_mpp {
4126                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4127                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4128                 // indicates there are more HTLCs coming.
4129                 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.
4130                 let payment_id = PaymentId([42; 32]);
4131                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4132                         RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4133                 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4134                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4135                         &None, session_privs[0]).unwrap();
4136                 check_added_monitors!(nodes[0], 1);
4137                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4138                 assert_eq!(events.len(), 1);
4139                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4140                 // hop should *not* yet generate any PaymentClaimable event(s).
4141                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4142                 our_payment_hash
4143         } else {
4144                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4145         };
4146
4147         let mut block = Block {
4148                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
4149                 txdata: vec![],
4150         };
4151         connect_block(&nodes[0], &block);
4152         connect_block(&nodes[1], &block);
4153         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4154         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4155                 block.header.prev_blockhash = block.block_hash();
4156                 connect_block(&nodes[0], &block);
4157                 connect_block(&nodes[1], &block);
4158         }
4159
4160         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4161
4162         check_added_monitors!(nodes[1], 1);
4163         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4164         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4165         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4166         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4167         assert!(htlc_timeout_updates.update_fee.is_none());
4168
4169         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4170         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4171         // 100_000 msat as u64, followed by the height at which we failed back above
4172         let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4173         expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4174         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4175 }
4176
4177 #[test]
4178 fn test_htlc_timeout() {
4179         do_test_htlc_timeout(true);
4180         do_test_htlc_timeout(false);
4181 }
4182
4183 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4184         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4185         let chanmon_cfgs = create_chanmon_cfgs(3);
4186         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4187         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4188         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4189         create_announced_chan_between_nodes(&nodes, 0, 1);
4190         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4191
4192         // Make sure all nodes are at the same starting height
4193         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4194         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4195         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4196
4197         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4198         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4199         nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4200                 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4201         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4202         check_added_monitors!(nodes[1], 1);
4203
4204         // Now attempt to route a second payment, which should be placed in the holding cell
4205         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4206         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4207         sending_node.node.send_payment_with_route(&route, second_payment_hash,
4208                 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4209         if forwarded_htlc {
4210                 check_added_monitors!(nodes[0], 1);
4211                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4212                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4213                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4214                 expect_pending_htlcs_forwardable!(nodes[1]);
4215         }
4216         check_added_monitors!(nodes[1], 0);
4217
4218         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4219         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4220         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4221         connect_blocks(&nodes[1], 1);
4222
4223         if forwarded_htlc {
4224                 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 }]);
4225                 check_added_monitors!(nodes[1], 1);
4226                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4227                 assert_eq!(fail_commit.len(), 1);
4228                 match fail_commit[0] {
4229                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4230                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4231                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4232                         },
4233                         _ => unreachable!(),
4234                 }
4235                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4236         } else {
4237                 expect_payment_failed!(nodes[1], second_payment_hash, false);
4238         }
4239 }
4240
4241 #[test]
4242 fn test_holding_cell_htlc_add_timeouts() {
4243         do_test_holding_cell_htlc_add_timeouts(false);
4244         do_test_holding_cell_htlc_add_timeouts(true);
4245 }
4246
4247 macro_rules! check_spendable_outputs {
4248         ($node: expr, $keysinterface: expr) => {
4249                 {
4250                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4251                         let mut txn = Vec::new();
4252                         let mut all_outputs = Vec::new();
4253                         let secp_ctx = Secp256k1::new();
4254                         for event in events.drain(..) {
4255                                 match event {
4256                                         Event::SpendableOutputs { mut outputs } => {
4257                                                 for outp in outputs.drain(..) {
4258                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4259                                                         all_outputs.push(outp);
4260                                                 }
4261                                         },
4262                                         _ => panic!("Unexpected event"),
4263                                 };
4264                         }
4265                         if all_outputs.len() > 1 {
4266                                 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) {
4267                                         txn.push(tx);
4268                                 }
4269                         }
4270                         txn
4271                 }
4272         }
4273 }
4274
4275 #[test]
4276 fn test_claim_sizeable_push_msat() {
4277         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4278         let chanmon_cfgs = create_chanmon_cfgs(2);
4279         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4280         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4281         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4282
4283         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4284         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4285         check_closed_broadcast!(nodes[1], true);
4286         check_added_monitors!(nodes[1], 1);
4287         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4288         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4289         assert_eq!(node_txn.len(), 1);
4290         check_spends!(node_txn[0], chan.3);
4291         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
4292
4293         mine_transaction(&nodes[1], &node_txn[0]);
4294         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4295
4296         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4297         assert_eq!(spend_txn.len(), 1);
4298         assert_eq!(spend_txn[0].input.len(), 1);
4299         check_spends!(spend_txn[0], node_txn[0]);
4300         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4301 }
4302
4303 #[test]
4304 fn test_claim_on_remote_sizeable_push_msat() {
4305         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4306         // to_remote output is encumbered by a P2WPKH
4307         let chanmon_cfgs = create_chanmon_cfgs(2);
4308         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4309         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4310         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4311
4312         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4313         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4314         check_closed_broadcast!(nodes[0], true);
4315         check_added_monitors!(nodes[0], 1);
4316         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4317
4318         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4319         assert_eq!(node_txn.len(), 1);
4320         check_spends!(node_txn[0], chan.3);
4321         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
4322
4323         mine_transaction(&nodes[1], &node_txn[0]);
4324         check_closed_broadcast!(nodes[1], true);
4325         check_added_monitors!(nodes[1], 1);
4326         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4327         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4328
4329         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4330         assert_eq!(spend_txn.len(), 1);
4331         check_spends!(spend_txn[0], node_txn[0]);
4332 }
4333
4334 #[test]
4335 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4336         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4337         // to_remote output is encumbered by a P2WPKH
4338
4339         let chanmon_cfgs = create_chanmon_cfgs(2);
4340         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4341         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4342         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4343
4344         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4345         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4346         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4347         assert_eq!(revoked_local_txn[0].input.len(), 1);
4348         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4349
4350         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4351         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4352         check_closed_broadcast!(nodes[1], true);
4353         check_added_monitors!(nodes[1], 1);
4354         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4355
4356         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4357         mine_transaction(&nodes[1], &node_txn[0]);
4358         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4359
4360         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4361         assert_eq!(spend_txn.len(), 3);
4362         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4363         check_spends!(spend_txn[1], node_txn[0]);
4364         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4365 }
4366
4367 #[test]
4368 fn test_static_spendable_outputs_preimage_tx() {
4369         let chanmon_cfgs = create_chanmon_cfgs(2);
4370         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4371         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4372         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4373
4374         // Create some initial channels
4375         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4376
4377         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4378
4379         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4380         assert_eq!(commitment_tx[0].input.len(), 1);
4381         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4382
4383         // Settle A's commitment tx on B's chain
4384         nodes[1].node.claim_funds(payment_preimage);
4385         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4386         check_added_monitors!(nodes[1], 1);
4387         mine_transaction(&nodes[1], &commitment_tx[0]);
4388         check_added_monitors!(nodes[1], 1);
4389         let events = nodes[1].node.get_and_clear_pending_msg_events();
4390         match events[0] {
4391                 MessageSendEvent::UpdateHTLCs { .. } => {},
4392                 _ => panic!("Unexpected event"),
4393         }
4394         match events[1] {
4395                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4396                 _ => panic!("Unexepected event"),
4397         }
4398
4399         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4400         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4401         assert_eq!(node_txn.len(), 1);
4402         check_spends!(node_txn[0], commitment_tx[0]);
4403         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4404
4405         mine_transaction(&nodes[1], &node_txn[0]);
4406         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4407         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4408
4409         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4410         assert_eq!(spend_txn.len(), 1);
4411         check_spends!(spend_txn[0], node_txn[0]);
4412 }
4413
4414 #[test]
4415 fn test_static_spendable_outputs_timeout_tx() {
4416         let chanmon_cfgs = create_chanmon_cfgs(2);
4417         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4418         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4419         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4420
4421         // Create some initial channels
4422         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4423
4424         // Rebalance the network a bit by relaying one payment through all the channels ...
4425         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4426
4427         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4428
4429         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4430         assert_eq!(commitment_tx[0].input.len(), 1);
4431         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4432
4433         // Settle A's commitment tx on B' chain
4434         mine_transaction(&nodes[1], &commitment_tx[0]);
4435         check_added_monitors!(nodes[1], 1);
4436         let events = nodes[1].node.get_and_clear_pending_msg_events();
4437         match events[0] {
4438                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4439                 _ => panic!("Unexpected event"),
4440         }
4441         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4442
4443         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4444         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4445         assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4446         check_spends!(node_txn[0],  commitment_tx[0].clone());
4447         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4448
4449         mine_transaction(&nodes[1], &node_txn[0]);
4450         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4451         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4452         expect_payment_failed!(nodes[1], our_payment_hash, false);
4453
4454         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4455         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4456         check_spends!(spend_txn[0], commitment_tx[0]);
4457         check_spends!(spend_txn[1], node_txn[0]);
4458         check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4459 }
4460
4461 #[test]
4462 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4463         let chanmon_cfgs = create_chanmon_cfgs(2);
4464         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4465         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4466         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4467
4468         // Create some initial channels
4469         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4470
4471         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4472         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4473         assert_eq!(revoked_local_txn[0].input.len(), 1);
4474         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4475
4476         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4477
4478         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4479         check_closed_broadcast!(nodes[1], true);
4480         check_added_monitors!(nodes[1], 1);
4481         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4482
4483         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4484         assert_eq!(node_txn.len(), 1);
4485         assert_eq!(node_txn[0].input.len(), 2);
4486         check_spends!(node_txn[0], revoked_local_txn[0]);
4487
4488         mine_transaction(&nodes[1], &node_txn[0]);
4489         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4490
4491         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4492         assert_eq!(spend_txn.len(), 1);
4493         check_spends!(spend_txn[0], node_txn[0]);
4494 }
4495
4496 #[test]
4497 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4498         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4499         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4500         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4501         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4502         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4503
4504         // Create some initial channels
4505         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4506
4507         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4508         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4509         assert_eq!(revoked_local_txn[0].input.len(), 1);
4510         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4511
4512         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4513
4514         // A will generate HTLC-Timeout from revoked commitment tx
4515         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4516         check_closed_broadcast!(nodes[0], true);
4517         check_added_monitors!(nodes[0], 1);
4518         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4519         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4520
4521         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4522         assert_eq!(revoked_htlc_txn.len(), 1);
4523         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4524         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4525         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4526         assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4527
4528         // B will generate justice tx from A's revoked commitment/HTLC tx
4529         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4530         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4531         check_closed_broadcast!(nodes[1], true);
4532         check_added_monitors!(nodes[1], 1);
4533         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4534
4535         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4536         assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4537         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4538         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4539         // transactions next...
4540         assert_eq!(node_txn[0].input.len(), 3);
4541         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4542
4543         assert_eq!(node_txn[1].input.len(), 2);
4544         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4545         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4546                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4547         } else {
4548                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4549                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4550         }
4551
4552         mine_transaction(&nodes[1], &node_txn[1]);
4553         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4554
4555         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4556         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4557         assert_eq!(spend_txn.len(), 1);
4558         assert_eq!(spend_txn[0].input.len(), 1);
4559         check_spends!(spend_txn[0], node_txn[1]);
4560 }
4561
4562 #[test]
4563 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4564         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4565         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4566         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4567         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4568         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4569
4570         // Create some initial channels
4571         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4572
4573         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4574         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4575         assert_eq!(revoked_local_txn[0].input.len(), 1);
4576         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4577
4578         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4579         assert_eq!(revoked_local_txn[0].output.len(), 2);
4580
4581         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4582
4583         // B will generate HTLC-Success from revoked commitment tx
4584         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4585         check_closed_broadcast!(nodes[1], true);
4586         check_added_monitors!(nodes[1], 1);
4587         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4588         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4589
4590         assert_eq!(revoked_htlc_txn.len(), 1);
4591         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4592         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4593         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4594
4595         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4596         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4597         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4598
4599         // A will generate justice tx from B's revoked commitment/HTLC tx
4600         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4601         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4602         check_closed_broadcast!(nodes[0], true);
4603         check_added_monitors!(nodes[0], 1);
4604         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4605
4606         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4607         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4608
4609         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4610         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4611         // transactions next...
4612         assert_eq!(node_txn[0].input.len(), 2);
4613         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4614         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4615                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4616         } else {
4617                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4618                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4619         }
4620
4621         assert_eq!(node_txn[1].input.len(), 1);
4622         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4623
4624         mine_transaction(&nodes[0], &node_txn[1]);
4625         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4626
4627         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4628         // didn't try to generate any new transactions.
4629
4630         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4631         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4632         assert_eq!(spend_txn.len(), 3);
4633         assert_eq!(spend_txn[0].input.len(), 1);
4634         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4635         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4636         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4637         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4638 }
4639
4640 #[test]
4641 fn test_onchain_to_onchain_claim() {
4642         // Test that in case of channel closure, we detect the state of output and claim HTLC
4643         // on downstream peer's remote commitment tx.
4644         // First, have C claim an HTLC against its own latest commitment transaction.
4645         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4646         // channel.
4647         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4648         // gets broadcast.
4649
4650         let chanmon_cfgs = create_chanmon_cfgs(3);
4651         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4652         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4653         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4654
4655         // Create some initial channels
4656         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4657         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4658
4659         // Ensure all nodes are at the same height
4660         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4661         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4662         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4663         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4664
4665         // Rebalance the network a bit by relaying one payment through all the channels ...
4666         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4667         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4668
4669         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4670         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4671         check_spends!(commitment_tx[0], chan_2.3);
4672         nodes[2].node.claim_funds(payment_preimage);
4673         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4674         check_added_monitors!(nodes[2], 1);
4675         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4676         assert!(updates.update_add_htlcs.is_empty());
4677         assert!(updates.update_fail_htlcs.is_empty());
4678         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4679         assert!(updates.update_fail_malformed_htlcs.is_empty());
4680
4681         mine_transaction(&nodes[2], &commitment_tx[0]);
4682         check_closed_broadcast!(nodes[2], true);
4683         check_added_monitors!(nodes[2], 1);
4684         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4685
4686         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4687         assert_eq!(c_txn.len(), 1);
4688         check_spends!(c_txn[0], commitment_tx[0]);
4689         assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4690         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4691         assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4692
4693         // 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
4694         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
4695         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone(), c_txn[0].clone()]});
4696         check_added_monitors!(nodes[1], 1);
4697         let events = nodes[1].node.get_and_clear_pending_events();
4698         assert_eq!(events.len(), 2);
4699         match events[0] {
4700                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4701                 _ => panic!("Unexpected event"),
4702         }
4703         match events[1] {
4704                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4705                         assert_eq!(fee_earned_msat, Some(1000));
4706                         assert_eq!(prev_channel_id, Some(chan_1.2));
4707                         assert_eq!(claim_from_onchain_tx, true);
4708                         assert_eq!(next_channel_id, Some(chan_2.2));
4709                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4710                 },
4711                 _ => panic!("Unexpected event"),
4712         }
4713         check_added_monitors!(nodes[1], 1);
4714         let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4715         assert_eq!(msg_events.len(), 3);
4716         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4717         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4718
4719         match nodes_2_event {
4720                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4721                 _ => panic!("Unexpected event"),
4722         }
4723
4724         match nodes_0_event {
4725                 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, .. } } => {
4726                         assert!(update_add_htlcs.is_empty());
4727                         assert!(update_fail_htlcs.is_empty());
4728                         assert_eq!(update_fulfill_htlcs.len(), 1);
4729                         assert!(update_fail_malformed_htlcs.is_empty());
4730                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4731                 },
4732                 _ => panic!("Unexpected event"),
4733         };
4734
4735         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4736         match msg_events[0] {
4737                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4738                 _ => panic!("Unexpected event"),
4739         }
4740
4741         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4742         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4743         mine_transaction(&nodes[1], &commitment_tx[0]);
4744         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4745         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4746         // ChannelMonitor: HTLC-Success tx
4747         assert_eq!(b_txn.len(), 1);
4748         check_spends!(b_txn[0], commitment_tx[0]);
4749         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4750         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4751         assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1 + 1); // Success tx
4752
4753         check_closed_broadcast!(nodes[1], true);
4754         check_added_monitors!(nodes[1], 1);
4755 }
4756
4757 #[test]
4758 fn test_duplicate_payment_hash_one_failure_one_success() {
4759         // Topology : A --> B --> C --> D
4760         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4761         // Note that because C will refuse to generate two payment secrets for the same payment hash,
4762         // we forward one of the payments onwards to D.
4763         let chanmon_cfgs = create_chanmon_cfgs(4);
4764         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4765         // When this test was written, the default base fee floated based on the HTLC count.
4766         // It is now fixed, so we simply set the fee to the expected value here.
4767         let mut config = test_default_channel_config();
4768         config.channel_config.forwarding_fee_base_msat = 196;
4769         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4770                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4771         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4772
4773         create_announced_chan_between_nodes(&nodes, 0, 1);
4774         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4775         create_announced_chan_between_nodes(&nodes, 2, 3);
4776
4777         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4778         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4779         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4780         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4781         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4782
4783         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4784
4785         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4786         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4787         // script push size limit so that the below script length checks match
4788         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4789         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4790                 .with_features(nodes[3].node.invoice_features());
4791         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000, TEST_FINAL_CLTV - 40);
4792         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4793
4794         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4795         assert_eq!(commitment_txn[0].input.len(), 1);
4796         check_spends!(commitment_txn[0], chan_2.3);
4797
4798         mine_transaction(&nodes[1], &commitment_txn[0]);
4799         check_closed_broadcast!(nodes[1], true);
4800         check_added_monitors!(nodes[1], 1);
4801         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4802         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
4803
4804         let htlc_timeout_tx;
4805         { // Extract one of the two HTLC-Timeout transaction
4806                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4807                 // ChannelMonitor: timeout tx * 2-or-3
4808                 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4809
4810                 check_spends!(node_txn[0], commitment_txn[0]);
4811                 assert_eq!(node_txn[0].input.len(), 1);
4812                 assert_eq!(node_txn[0].output.len(), 1);
4813
4814                 if node_txn.len() > 2 {
4815                         check_spends!(node_txn[1], commitment_txn[0]);
4816                         assert_eq!(node_txn[1].input.len(), 1);
4817                         assert_eq!(node_txn[1].output.len(), 1);
4818                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4819
4820                         check_spends!(node_txn[2], commitment_txn[0]);
4821                         assert_eq!(node_txn[2].input.len(), 1);
4822                         assert_eq!(node_txn[2].output.len(), 1);
4823                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4824                 } else {
4825                         check_spends!(node_txn[1], commitment_txn[0]);
4826                         assert_eq!(node_txn[1].input.len(), 1);
4827                         assert_eq!(node_txn[1].output.len(), 1);
4828                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4829                 }
4830
4831                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4832                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4833                 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
4834                 // (with value 900 sats) will be claimed in the below `claim_funds` call.
4835                 if node_txn.len() > 2 {
4836                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4837                         htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
4838                 } else {
4839                         htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
4840                 }
4841         }
4842
4843         nodes[2].node.claim_funds(our_payment_preimage);
4844         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4845
4846         mine_transaction(&nodes[2], &commitment_txn[0]);
4847         check_added_monitors!(nodes[2], 2);
4848         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4849         let events = nodes[2].node.get_and_clear_pending_msg_events();
4850         match events[0] {
4851                 MessageSendEvent::UpdateHTLCs { .. } => {},
4852                 _ => panic!("Unexpected event"),
4853         }
4854         match events[1] {
4855                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4856                 _ => panic!("Unexepected event"),
4857         }
4858         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4859         assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4860         check_spends!(htlc_success_txn[0], commitment_txn[0]);
4861         check_spends!(htlc_success_txn[1], commitment_txn[0]);
4862         assert_eq!(htlc_success_txn[0].input.len(), 1);
4863         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4864         assert_eq!(htlc_success_txn[1].input.len(), 1);
4865         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4866         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4867         assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4868
4869         mine_transaction(&nodes[1], &htlc_timeout_tx);
4870         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4871         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 }]);
4872         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4873         assert!(htlc_updates.update_add_htlcs.is_empty());
4874         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4875         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4876         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4877         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4878         check_added_monitors!(nodes[1], 1);
4879
4880         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4881         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4882         {
4883                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4884         }
4885         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
4886
4887         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4888         mine_transaction(&nodes[1], &htlc_success_txn[1]);
4889         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
4890         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4891         assert!(updates.update_add_htlcs.is_empty());
4892         assert!(updates.update_fail_htlcs.is_empty());
4893         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4894         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
4895         assert!(updates.update_fail_malformed_htlcs.is_empty());
4896         check_added_monitors!(nodes[1], 1);
4897
4898         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4899         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4900
4901         let events = nodes[0].node.get_and_clear_pending_events();
4902         match events[0] {
4903                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4904                         assert_eq!(*payment_preimage, our_payment_preimage);
4905                         assert_eq!(*payment_hash, duplicate_payment_hash);
4906                 }
4907                 _ => panic!("Unexpected event"),
4908         }
4909 }
4910
4911 #[test]
4912 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4913         let chanmon_cfgs = create_chanmon_cfgs(2);
4914         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4915         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4916         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4917
4918         // Create some initial channels
4919         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4920
4921         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
4922         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4923         assert_eq!(local_txn.len(), 1);
4924         assert_eq!(local_txn[0].input.len(), 1);
4925         check_spends!(local_txn[0], chan_1.3);
4926
4927         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4928         nodes[1].node.claim_funds(payment_preimage);
4929         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
4930         check_added_monitors!(nodes[1], 1);
4931
4932         mine_transaction(&nodes[1], &local_txn[0]);
4933         check_added_monitors!(nodes[1], 1);
4934         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4935         let events = nodes[1].node.get_and_clear_pending_msg_events();
4936         match events[0] {
4937                 MessageSendEvent::UpdateHTLCs { .. } => {},
4938                 _ => panic!("Unexpected event"),
4939         }
4940         match events[1] {
4941                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4942                 _ => panic!("Unexepected event"),
4943         }
4944         let node_tx = {
4945                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4946                 assert_eq!(node_txn.len(), 1);
4947                 assert_eq!(node_txn[0].input.len(), 1);
4948                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4949                 check_spends!(node_txn[0], local_txn[0]);
4950                 node_txn[0].clone()
4951         };
4952
4953         mine_transaction(&nodes[1], &node_tx);
4954         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4955
4956         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4957         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4958         assert_eq!(spend_txn.len(), 1);
4959         assert_eq!(spend_txn[0].input.len(), 1);
4960         check_spends!(spend_txn[0], node_tx);
4961         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4962 }
4963
4964 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4965         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4966         // unrevoked commitment transaction.
4967         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4968         // a remote RAA before they could be failed backwards (and combinations thereof).
4969         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4970         // use the same payment hashes.
4971         // Thus, we use a six-node network:
4972         //
4973         // A \         / E
4974         //    - C - D -
4975         // B /         \ F
4976         // And test where C fails back to A/B when D announces its latest commitment transaction
4977         let chanmon_cfgs = create_chanmon_cfgs(6);
4978         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4979         // When this test was written, the default base fee floated based on the HTLC count.
4980         // It is now fixed, so we simply set the fee to the expected value here.
4981         let mut config = test_default_channel_config();
4982         config.channel_config.forwarding_fee_base_msat = 196;
4983         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
4984                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4985         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4986
4987         let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
4988         let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4989         let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
4990         let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
4991         let chan_3_5  = create_announced_chan_between_nodes(&nodes, 3, 5);
4992
4993         // Rebalance and check output sanity...
4994         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
4995         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
4996         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
4997
4998         let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
4999                 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
5000         // 0th HTLC:
5001         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
5002         // 1st HTLC:
5003         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
5004         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5005         // 2nd HTLC:
5006         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
5007         // 3rd HTLC:
5008         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
5009         // 4th HTLC:
5010         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5011         // 5th HTLC:
5012         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5013         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5014         // 6th HTLC:
5015         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());
5016         // 7th HTLC:
5017         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());
5018
5019         // 8th HTLC:
5020         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5021         // 9th HTLC:
5022         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5023         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
5024
5025         // 10th HTLC:
5026         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
5027         // 11th HTLC:
5028         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5029         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());
5030
5031         // Double-check that six of the new HTLC were added
5032         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5033         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5034         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5035         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5036
5037         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5038         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5039         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5040         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5041         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5042         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5043         check_added_monitors!(nodes[4], 0);
5044
5045         let failed_destinations = vec![
5046                 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5047                 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5048                 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5049                 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5050         ];
5051         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5052         check_added_monitors!(nodes[4], 1);
5053
5054         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5055         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5056         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5057         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5058         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5059         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5060
5061         // Fail 3rd below-dust and 7th above-dust HTLCs
5062         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5063         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5064         check_added_monitors!(nodes[5], 0);
5065
5066         let failed_destinations_2 = vec![
5067                 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5068                 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5069         ];
5070         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5071         check_added_monitors!(nodes[5], 1);
5072
5073         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5074         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5075         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5076         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5077
5078         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5079
5080         // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5081         let failed_destinations_3 = vec![
5082                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5083                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5084                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5085                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5086                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5087                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5088         ];
5089         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5090         check_added_monitors!(nodes[3], 1);
5091         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5092         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5093         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5094         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5095         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5096         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5097         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5098         if deliver_last_raa {
5099                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5100         } else {
5101                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5102         }
5103
5104         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5105         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5106         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5107         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5108         //
5109         // We now broadcast the latest commitment transaction, which *should* result in failures for
5110         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5111         // the non-broadcast above-dust HTLCs.
5112         //
5113         // Alternatively, we may broadcast the previous commitment transaction, which should only
5114         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5115         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5116
5117         if announce_latest {
5118                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5119         } else {
5120                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5121         }
5122         let events = nodes[2].node.get_and_clear_pending_events();
5123         let close_event = if deliver_last_raa {
5124                 assert_eq!(events.len(), 2 + 6);
5125                 events.last().clone().unwrap()
5126         } else {
5127                 assert_eq!(events.len(), 1);
5128                 events.last().clone().unwrap()
5129         };
5130         match close_event {
5131                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5132                 _ => panic!("Unexpected event"),
5133         }
5134
5135         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5136         check_closed_broadcast!(nodes[2], true);
5137         if deliver_last_raa {
5138                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5139
5140                 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();
5141                 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5142         } else {
5143                 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5144                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5145                 } else {
5146                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5147                 };
5148
5149                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5150         }
5151         check_added_monitors!(nodes[2], 3);
5152
5153         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5154         assert_eq!(cs_msgs.len(), 2);
5155         let mut a_done = false;
5156         for msg in cs_msgs {
5157                 match msg {
5158                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5159                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5160                                 // should be failed-backwards here.
5161                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5162                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5163                                         for htlc in &updates.update_fail_htlcs {
5164                                                 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 });
5165                                         }
5166                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5167                                         assert!(!a_done);
5168                                         a_done = true;
5169                                         &nodes[0]
5170                                 } else {
5171                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5172                                         for htlc in &updates.update_fail_htlcs {
5173                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5174                                         }
5175                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5176                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5177                                         &nodes[1]
5178                                 };
5179                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5180                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5181                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5182                                 if announce_latest {
5183                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5184                                         if *node_id == nodes[0].node.get_our_node_id() {
5185                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5186                                         }
5187                                 }
5188                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5189                         },
5190                         _ => panic!("Unexpected event"),
5191                 }
5192         }
5193
5194         let as_events = nodes[0].node.get_and_clear_pending_events();
5195         assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5196         let mut as_failds = HashSet::new();
5197         let mut as_updates = 0;
5198         for event in as_events.iter() {
5199                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5200                         assert!(as_failds.insert(*payment_hash));
5201                         if *payment_hash != payment_hash_2 {
5202                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5203                         } else {
5204                                 assert!(!payment_failed_permanently);
5205                         }
5206                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5207                                 as_updates += 1;
5208                         }
5209                 } else if let &Event::PaymentFailed { .. } = event {
5210                 } else { panic!("Unexpected event"); }
5211         }
5212         assert!(as_failds.contains(&payment_hash_1));
5213         assert!(as_failds.contains(&payment_hash_2));
5214         if announce_latest {
5215                 assert!(as_failds.contains(&payment_hash_3));
5216                 assert!(as_failds.contains(&payment_hash_5));
5217         }
5218         assert!(as_failds.contains(&payment_hash_6));
5219
5220         let bs_events = nodes[1].node.get_and_clear_pending_events();
5221         assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5222         let mut bs_failds = HashSet::new();
5223         let mut bs_updates = 0;
5224         for event in bs_events.iter() {
5225                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5226                         assert!(bs_failds.insert(*payment_hash));
5227                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5228                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5229                         } else {
5230                                 assert!(!payment_failed_permanently);
5231                         }
5232                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5233                                 bs_updates += 1;
5234                         }
5235                 } else if let &Event::PaymentFailed { .. } = event {
5236                 } else { panic!("Unexpected event"); }
5237         }
5238         assert!(bs_failds.contains(&payment_hash_1));
5239         assert!(bs_failds.contains(&payment_hash_2));
5240         if announce_latest {
5241                 assert!(bs_failds.contains(&payment_hash_4));
5242         }
5243         assert!(bs_failds.contains(&payment_hash_5));
5244
5245         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5246         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5247         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5248         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5249         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5250         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5251 }
5252
5253 #[test]
5254 fn test_fail_backwards_latest_remote_announce_a() {
5255         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5256 }
5257
5258 #[test]
5259 fn test_fail_backwards_latest_remote_announce_b() {
5260         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5261 }
5262
5263 #[test]
5264 fn test_fail_backwards_previous_remote_announce() {
5265         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5266         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5267         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5268 }
5269
5270 #[test]
5271 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5272         let chanmon_cfgs = create_chanmon_cfgs(2);
5273         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5274         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5275         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5276
5277         // Create some initial channels
5278         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5279
5280         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5281         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5282         assert_eq!(local_txn[0].input.len(), 1);
5283         check_spends!(local_txn[0], chan_1.3);
5284
5285         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5286         mine_transaction(&nodes[0], &local_txn[0]);
5287         check_closed_broadcast!(nodes[0], true);
5288         check_added_monitors!(nodes[0], 1);
5289         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5290         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5291
5292         let htlc_timeout = {
5293                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5294                 assert_eq!(node_txn.len(), 1);
5295                 assert_eq!(node_txn[0].input.len(), 1);
5296                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5297                 check_spends!(node_txn[0], local_txn[0]);
5298                 node_txn[0].clone()
5299         };
5300
5301         mine_transaction(&nodes[0], &htlc_timeout);
5302         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5303         expect_payment_failed!(nodes[0], our_payment_hash, false);
5304
5305         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5306         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5307         assert_eq!(spend_txn.len(), 3);
5308         check_spends!(spend_txn[0], local_txn[0]);
5309         assert_eq!(spend_txn[1].input.len(), 1);
5310         check_spends!(spend_txn[1], htlc_timeout);
5311         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5312         assert_eq!(spend_txn[2].input.len(), 2);
5313         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5314         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5315                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5316 }
5317
5318 #[test]
5319 fn test_key_derivation_params() {
5320         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5321         // manager rotation to test that `channel_keys_id` returned in
5322         // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5323         // then derive a `delayed_payment_key`.
5324
5325         let chanmon_cfgs = create_chanmon_cfgs(3);
5326
5327         // We manually create the node configuration to backup the seed.
5328         let seed = [42; 32];
5329         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5330         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);
5331         let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5332         let scorer = Mutex::new(test_utils::TestScorer::new());
5333         let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5334         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)) };
5335         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5336         node_cfgs.remove(0);
5337         node_cfgs.insert(0, node);
5338
5339         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5340         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5341
5342         // Create some initial channels
5343         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5344         // for node 0
5345         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5346         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5347         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5348
5349         // Ensure all nodes are at the same height
5350         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5351         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5352         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5353         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5354
5355         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5356         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5357         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5358         assert_eq!(local_txn_1[0].input.len(), 1);
5359         check_spends!(local_txn_1[0], chan_1.3);
5360
5361         // We check funding pubkey are unique
5362         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]));
5363         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]));
5364         if from_0_funding_key_0 == from_1_funding_key_0
5365             || from_0_funding_key_0 == from_1_funding_key_1
5366             || from_0_funding_key_1 == from_1_funding_key_0
5367             || from_0_funding_key_1 == from_1_funding_key_1 {
5368                 panic!("Funding pubkeys aren't unique");
5369         }
5370
5371         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5372         mine_transaction(&nodes[0], &local_txn_1[0]);
5373         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5374         check_closed_broadcast!(nodes[0], true);
5375         check_added_monitors!(nodes[0], 1);
5376         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5377
5378         let htlc_timeout = {
5379                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5380                 assert_eq!(node_txn.len(), 1);
5381                 assert_eq!(node_txn[0].input.len(), 1);
5382                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5383                 check_spends!(node_txn[0], local_txn_1[0]);
5384                 node_txn[0].clone()
5385         };
5386
5387         mine_transaction(&nodes[0], &htlc_timeout);
5388         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5389         expect_payment_failed!(nodes[0], our_payment_hash, false);
5390
5391         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5392         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5393         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5394         assert_eq!(spend_txn.len(), 3);
5395         check_spends!(spend_txn[0], local_txn_1[0]);
5396         assert_eq!(spend_txn[1].input.len(), 1);
5397         check_spends!(spend_txn[1], htlc_timeout);
5398         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5399         assert_eq!(spend_txn[2].input.len(), 2);
5400         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5401         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5402                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5403 }
5404
5405 #[test]
5406 fn test_static_output_closing_tx() {
5407         let chanmon_cfgs = create_chanmon_cfgs(2);
5408         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5409         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5410         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5411
5412         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5413
5414         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5415         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5416
5417         mine_transaction(&nodes[0], &closing_tx);
5418         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5419         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5420
5421         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5422         assert_eq!(spend_txn.len(), 1);
5423         check_spends!(spend_txn[0], closing_tx);
5424
5425         mine_transaction(&nodes[1], &closing_tx);
5426         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5427         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5428
5429         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5430         assert_eq!(spend_txn.len(), 1);
5431         check_spends!(spend_txn[0], closing_tx);
5432 }
5433
5434 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5435         let chanmon_cfgs = create_chanmon_cfgs(2);
5436         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5437         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5438         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5439         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5440
5441         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5442
5443         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5444         // present in B's local commitment transaction, but none of A's commitment transactions.
5445         nodes[1].node.claim_funds(payment_preimage);
5446         check_added_monitors!(nodes[1], 1);
5447         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5448
5449         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5450         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5451         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5452
5453         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5454         check_added_monitors!(nodes[0], 1);
5455         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5456         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5457         check_added_monitors!(nodes[1], 1);
5458
5459         let starting_block = nodes[1].best_block_info();
5460         let mut block = Block {
5461                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5462                 txdata: vec![],
5463         };
5464         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5465                 connect_block(&nodes[1], &block);
5466                 block.header.prev_blockhash = block.block_hash();
5467         }
5468         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5469         check_closed_broadcast!(nodes[1], true);
5470         check_added_monitors!(nodes[1], 1);
5471         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5472 }
5473
5474 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5475         let chanmon_cfgs = create_chanmon_cfgs(2);
5476         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5477         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5478         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5479         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5480
5481         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5482         nodes[0].node.send_payment_with_route(&route, payment_hash,
5483                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5484         check_added_monitors!(nodes[0], 1);
5485
5486         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5487
5488         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5489         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5490         // to "time out" the HTLC.
5491
5492         let starting_block = nodes[1].best_block_info();
5493         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5494
5495         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5496                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5497                 header.prev_blockhash = header.block_hash();
5498         }
5499         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5500         check_closed_broadcast!(nodes[0], true);
5501         check_added_monitors!(nodes[0], 1);
5502         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5503 }
5504
5505 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5506         let chanmon_cfgs = create_chanmon_cfgs(3);
5507         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5508         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5509         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5510         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5511
5512         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5513         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5514         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5515         // actually revoked.
5516         let htlc_value = if use_dust { 50000 } else { 3000000 };
5517         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5518         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5519         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5520         check_added_monitors!(nodes[1], 1);
5521
5522         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5523         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5524         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5525         check_added_monitors!(nodes[0], 1);
5526         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5527         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5528         check_added_monitors!(nodes[1], 1);
5529         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5530         check_added_monitors!(nodes[1], 1);
5531         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5532
5533         if check_revoke_no_close {
5534                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5535                 check_added_monitors!(nodes[0], 1);
5536         }
5537
5538         let starting_block = nodes[1].best_block_info();
5539         let mut block = Block {
5540                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5541                 txdata: vec![],
5542         };
5543         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5544                 connect_block(&nodes[0], &block);
5545                 block.header.prev_blockhash = block.block_hash();
5546         }
5547         if !check_revoke_no_close {
5548                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5549                 check_closed_broadcast!(nodes[0], true);
5550                 check_added_monitors!(nodes[0], 1);
5551                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5552         } else {
5553                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5554         }
5555 }
5556
5557 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5558 // There are only a few cases to test here:
5559 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5560 //    broadcastable commitment transactions result in channel closure,
5561 //  * its included in an unrevoked-but-previous remote commitment transaction,
5562 //  * its included in the latest remote or local commitment transactions.
5563 // We test each of the three possible commitment transactions individually and use both dust and
5564 // non-dust HTLCs.
5565 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5566 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5567 // tested for at least one of the cases in other tests.
5568 #[test]
5569 fn htlc_claim_single_commitment_only_a() {
5570         do_htlc_claim_local_commitment_only(true);
5571         do_htlc_claim_local_commitment_only(false);
5572
5573         do_htlc_claim_current_remote_commitment_only(true);
5574         do_htlc_claim_current_remote_commitment_only(false);
5575 }
5576
5577 #[test]
5578 fn htlc_claim_single_commitment_only_b() {
5579         do_htlc_claim_previous_remote_commitment_only(true, false);
5580         do_htlc_claim_previous_remote_commitment_only(false, false);
5581         do_htlc_claim_previous_remote_commitment_only(true, true);
5582         do_htlc_claim_previous_remote_commitment_only(false, true);
5583 }
5584
5585 #[test]
5586 #[should_panic]
5587 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5588         let chanmon_cfgs = create_chanmon_cfgs(2);
5589         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5590         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5591         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5592         // Force duplicate randomness for every get-random call
5593         for node in nodes.iter() {
5594                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5595         }
5596
5597         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5598         let channel_value_satoshis=10000;
5599         let push_msat=10001;
5600         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5601         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5602         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5603         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5604
5605         // Create a second channel with the same random values. This used to panic due to a colliding
5606         // channel_id, but now panics due to a colliding outbound SCID alias.
5607         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5608 }
5609
5610 #[test]
5611 fn bolt2_open_channel_sending_node_checks_part2() {
5612         let chanmon_cfgs = create_chanmon_cfgs(2);
5613         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5614         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5615         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5616
5617         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5618         let channel_value_satoshis=2^24;
5619         let push_msat=10001;
5620         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5621
5622         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5623         let channel_value_satoshis=10000;
5624         // Test when push_msat is equal to 1000 * funding_satoshis.
5625         let push_msat=1000*channel_value_satoshis+1;
5626         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5627
5628         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5629         let channel_value_satoshis=10000;
5630         let push_msat=10001;
5631         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
5632         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5633         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5634
5635         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5636         // 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
5637         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5638
5639         // 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.
5640         assert!(BREAKDOWN_TIMEOUT>0);
5641         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5642
5643         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5644         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5645         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5646
5647         // 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.
5648         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5649         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5650         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5651         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5652         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5653 }
5654
5655 #[test]
5656 fn bolt2_open_channel_sane_dust_limit() {
5657         let chanmon_cfgs = create_chanmon_cfgs(2);
5658         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5659         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5660         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5661
5662         let channel_value_satoshis=1000000;
5663         let push_msat=10001;
5664         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5665         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5666         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5667         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5668
5669         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5670         let events = nodes[1].node.get_and_clear_pending_msg_events();
5671         let err_msg = match events[0] {
5672                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5673                         msg.clone()
5674                 },
5675                 _ => panic!("Unexpected event"),
5676         };
5677         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5678 }
5679
5680 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5681 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5682 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5683 // is no longer affordable once it's freed.
5684 #[test]
5685 fn test_fail_holding_cell_htlc_upon_free() {
5686         let chanmon_cfgs = create_chanmon_cfgs(2);
5687         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5688         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5689         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5690         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5691
5692         // First nodes[0] generates an update_fee, setting the channel's
5693         // pending_update_fee.
5694         {
5695                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5696                 *feerate_lock += 20;
5697         }
5698         nodes[0].node.timer_tick_occurred();
5699         check_added_monitors!(nodes[0], 1);
5700
5701         let events = nodes[0].node.get_and_clear_pending_msg_events();
5702         assert_eq!(events.len(), 1);
5703         let (update_msg, commitment_signed) = match events[0] {
5704                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5705                         (update_fee.as_ref(), commitment_signed)
5706                 },
5707                 _ => panic!("Unexpected event"),
5708         };
5709
5710         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5711
5712         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5713         let channel_reserve = chan_stat.channel_reserve_msat;
5714         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5715         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5716
5717         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5718         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5719         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5720
5721         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5722         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5723                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5724         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5725         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5726
5727         // Flush the pending fee update.
5728         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5729         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5730         check_added_monitors!(nodes[1], 1);
5731         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5732         check_added_monitors!(nodes[0], 1);
5733
5734         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5735         // HTLC, but now that the fee has been raised the payment will now fail, causing
5736         // us to surface its failure to the user.
5737         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5738         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5739         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);
5740         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 {}",
5741                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5742         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5743
5744         // Check that the payment failed to be sent out.
5745         let events = nodes[0].node.get_and_clear_pending_events();
5746         assert_eq!(events.len(), 2);
5747         match &events[0] {
5748                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5749                         assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5750                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5751                         assert_eq!(*payment_failed_permanently, false);
5752                         assert_eq!(*short_channel_id, Some(route.paths[0][0].short_channel_id));
5753                 },
5754                 _ => panic!("Unexpected event"),
5755         }
5756         match &events[1] {
5757                 &Event::PaymentFailed { ref payment_hash, .. } => {
5758                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5759                 },
5760                 _ => panic!("Unexpected event"),
5761         }
5762 }
5763
5764 // Test that if multiple HTLCs are released from the holding cell and one is
5765 // valid but the other is no longer valid upon release, the valid HTLC can be
5766 // successfully completed while the other one fails as expected.
5767 #[test]
5768 fn test_free_and_fail_holding_cell_htlcs() {
5769         let chanmon_cfgs = create_chanmon_cfgs(2);
5770         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5771         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5772         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5773         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5774
5775         // First nodes[0] generates an update_fee, setting the channel's
5776         // pending_update_fee.
5777         {
5778                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5779                 *feerate_lock += 200;
5780         }
5781         nodes[0].node.timer_tick_occurred();
5782         check_added_monitors!(nodes[0], 1);
5783
5784         let events = nodes[0].node.get_and_clear_pending_msg_events();
5785         assert_eq!(events.len(), 1);
5786         let (update_msg, commitment_signed) = match events[0] {
5787                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5788                         (update_fee.as_ref(), commitment_signed)
5789                 },
5790                 _ => panic!("Unexpected event"),
5791         };
5792
5793         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5794
5795         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5796         let channel_reserve = chan_stat.channel_reserve_msat;
5797         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5798         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5799
5800         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5801         let amt_1 = 20000;
5802         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
5803         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5804         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5805
5806         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5807         nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
5808                 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5809         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5810         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5811         let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5812         nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
5813                 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
5814         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5815         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5816
5817         // Flush the pending fee update.
5818         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5819         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5820         check_added_monitors!(nodes[1], 1);
5821         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5822         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5823         check_added_monitors!(nodes[0], 2);
5824
5825         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5826         // but now that the fee has been raised the second payment will now fail, causing us
5827         // to surface its failure to the user. The first payment should succeed.
5828         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5829         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5830         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);
5831         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 {}",
5832                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5833         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5834
5835         // Check that the second payment failed to be sent out.
5836         let events = nodes[0].node.get_and_clear_pending_events();
5837         assert_eq!(events.len(), 2);
5838         match &events[0] {
5839                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5840                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5841                         assert_eq!(payment_hash_2.clone(), *payment_hash);
5842                         assert_eq!(*payment_failed_permanently, false);
5843                         assert_eq!(*short_channel_id, Some(route_2.paths[0][0].short_channel_id));
5844                 },
5845                 _ => panic!("Unexpected event"),
5846         }
5847         match &events[1] {
5848                 &Event::PaymentFailed { ref payment_hash, .. } => {
5849                         assert_eq!(payment_hash_2.clone(), *payment_hash);
5850                 },
5851                 _ => panic!("Unexpected event"),
5852         }
5853
5854         // Complete the first payment and the RAA from the fee update.
5855         let (payment_event, send_raa_event) = {
5856                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5857                 assert_eq!(msgs.len(), 2);
5858                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5859         };
5860         let raa = match send_raa_event {
5861                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5862                 _ => panic!("Unexpected event"),
5863         };
5864         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5865         check_added_monitors!(nodes[1], 1);
5866         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5867         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5868         let events = nodes[1].node.get_and_clear_pending_events();
5869         assert_eq!(events.len(), 1);
5870         match events[0] {
5871                 Event::PendingHTLCsForwardable { .. } => {},
5872                 _ => panic!("Unexpected event"),
5873         }
5874         nodes[1].node.process_pending_htlc_forwards();
5875         let events = nodes[1].node.get_and_clear_pending_events();
5876         assert_eq!(events.len(), 1);
5877         match events[0] {
5878                 Event::PaymentClaimable { .. } => {},
5879                 _ => panic!("Unexpected event"),
5880         }
5881         nodes[1].node.claim_funds(payment_preimage_1);
5882         check_added_monitors!(nodes[1], 1);
5883         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5884
5885         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5886         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5887         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5888         expect_payment_sent!(nodes[0], payment_preimage_1);
5889 }
5890
5891 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
5892 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
5893 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
5894 // once it's freed.
5895 #[test]
5896 fn test_fail_holding_cell_htlc_upon_free_multihop() {
5897         let chanmon_cfgs = create_chanmon_cfgs(3);
5898         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5899         // When this test was written, the default base fee floated based on the HTLC count.
5900         // It is now fixed, so we simply set the fee to the expected value here.
5901         let mut config = test_default_channel_config();
5902         config.channel_config.forwarding_fee_base_msat = 196;
5903         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5904         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5905         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5906         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
5907
5908         // First nodes[1] generates an update_fee, setting the channel's
5909         // pending_update_fee.
5910         {
5911                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
5912                 *feerate_lock += 20;
5913         }
5914         nodes[1].node.timer_tick_occurred();
5915         check_added_monitors!(nodes[1], 1);
5916
5917         let events = nodes[1].node.get_and_clear_pending_msg_events();
5918         assert_eq!(events.len(), 1);
5919         let (update_msg, commitment_signed) = match events[0] {
5920                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5921                         (update_fee.as_ref(), commitment_signed)
5922                 },
5923                 _ => panic!("Unexpected event"),
5924         };
5925
5926         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
5927
5928         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
5929         let channel_reserve = chan_stat.channel_reserve_msat;
5930         let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
5931         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_0_1.2);
5932
5933         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5934         let feemsat = 239;
5935         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
5936         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
5937         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
5938         let payment_event = {
5939                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5940                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5941                 check_added_monitors!(nodes[0], 1);
5942
5943                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5944                 assert_eq!(events.len(), 1);
5945
5946                 SendEvent::from_event(events.remove(0))
5947         };
5948         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5949         check_added_monitors!(nodes[1], 0);
5950         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5951         expect_pending_htlcs_forwardable!(nodes[1]);
5952
5953         chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
5954         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5955
5956         // Flush the pending fee update.
5957         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
5958         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5959         check_added_monitors!(nodes[2], 1);
5960         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
5961         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
5962         check_added_monitors!(nodes[1], 2);
5963
5964         // A final RAA message is generated to finalize the fee update.
5965         let events = nodes[1].node.get_and_clear_pending_msg_events();
5966         assert_eq!(events.len(), 1);
5967
5968         let raa_msg = match &events[0] {
5969                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
5970                         msg.clone()
5971                 },
5972                 _ => panic!("Unexpected event"),
5973         };
5974
5975         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
5976         check_added_monitors!(nodes[2], 1);
5977         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
5978
5979         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
5980         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
5981         assert_eq!(process_htlc_forwards_event.len(), 2);
5982         match &process_htlc_forwards_event[0] {
5983                 &Event::PendingHTLCsForwardable { .. } => {},
5984                 _ => panic!("Unexpected event"),
5985         }
5986
5987         // In response, we call ChannelManager's process_pending_htlc_forwards
5988         nodes[1].node.process_pending_htlc_forwards();
5989         check_added_monitors!(nodes[1], 1);
5990
5991         // This causes the HTLC to be failed backwards.
5992         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
5993         assert_eq!(fail_event.len(), 1);
5994         let (fail_msg, commitment_signed) = match &fail_event[0] {
5995                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
5996                         assert_eq!(updates.update_add_htlcs.len(), 0);
5997                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
5998                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
5999                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6000                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6001                 },
6002                 _ => panic!("Unexpected event"),
6003         };
6004
6005         // Pass the failure messages back to nodes[0].
6006         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6007         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6008
6009         // Complete the HTLC failure+removal process.
6010         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6011         check_added_monitors!(nodes[0], 1);
6012         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6013         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6014         check_added_monitors!(nodes[1], 2);
6015         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6016         assert_eq!(final_raa_event.len(), 1);
6017         let raa = match &final_raa_event[0] {
6018                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6019                 _ => panic!("Unexpected event"),
6020         };
6021         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6022         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6023         check_added_monitors!(nodes[0], 1);
6024 }
6025
6026 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6027 // 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.
6028 //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.
6029
6030 #[test]
6031 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6032         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6033         let chanmon_cfgs = create_chanmon_cfgs(2);
6034         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6035         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6036         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6037         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6038
6039         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6040         route.paths[0][0].fee_msat = 100;
6041
6042         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6043                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6044                 ), true, APIError::ChannelUnavailable { ref err },
6045                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6046         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6047         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send less than their minimum HTLC value", 1);
6048 }
6049
6050 #[test]
6051 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6052         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6053         let chanmon_cfgs = create_chanmon_cfgs(2);
6054         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6055         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6056         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6057         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6058
6059         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6060         route.paths[0][0].fee_msat = 0;
6061         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6062                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6063                 true, APIError::ChannelUnavailable { ref err },
6064                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6065
6066         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6067         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6068 }
6069
6070 #[test]
6071 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6072         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6073         let chanmon_cfgs = create_chanmon_cfgs(2);
6074         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6075         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6076         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6077         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6078
6079         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6080         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6081                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6082         check_added_monitors!(nodes[0], 1);
6083         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6084         updates.update_add_htlcs[0].amount_msat = 0;
6085
6086         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6087         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6088         check_closed_broadcast!(nodes[1], true).unwrap();
6089         check_added_monitors!(nodes[1], 1);
6090         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6091 }
6092
6093 #[test]
6094 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6095         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6096         //It is enforced when constructing a route.
6097         let chanmon_cfgs = create_chanmon_cfgs(2);
6098         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6099         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6100         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6101         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6102
6103         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6104                 .with_features(nodes[1].node.invoice_features());
6105         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6106         route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6107         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6108                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6109                 ), true, APIError::InvalidRoute { ref err },
6110                 assert_eq!(err, &"Channel CLTV overflowed?"));
6111 }
6112
6113 #[test]
6114 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6115         //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.
6116         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6117         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6118         let chanmon_cfgs = create_chanmon_cfgs(2);
6119         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6120         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6121         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6122         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6123         let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6124                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6125
6126         for i in 0..max_accepted_htlcs {
6127                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6128                 let payment_event = {
6129                         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6130                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6131                         check_added_monitors!(nodes[0], 1);
6132
6133                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6134                         assert_eq!(events.len(), 1);
6135                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6136                                 assert_eq!(htlcs[0].htlc_id, i);
6137                         } else {
6138                                 assert!(false);
6139                         }
6140                         SendEvent::from_event(events.remove(0))
6141                 };
6142                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6143                 check_added_monitors!(nodes[1], 0);
6144                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6145
6146                 expect_pending_htlcs_forwardable!(nodes[1]);
6147                 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6148         }
6149         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6150         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6151                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6152                 ), true, APIError::ChannelUnavailable { ref err },
6153                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6154
6155         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6156         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
6157 }
6158
6159 #[test]
6160 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6161         //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.
6162         let chanmon_cfgs = create_chanmon_cfgs(2);
6163         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6164         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6165         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6166         let channel_value = 100000;
6167         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6168         let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6169
6170         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6171
6172         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6173         // Manually create a route over our max in flight (which our router normally automatically
6174         // limits us to.
6175         route.paths[0][0].fee_msat =  max_in_flight + 1;
6176         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6177                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6178                 ), true, APIError::ChannelUnavailable { ref err },
6179                 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)));
6180
6181         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6182         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);
6183
6184         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6185 }
6186
6187 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6188 #[test]
6189 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6190         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6191         let chanmon_cfgs = create_chanmon_cfgs(2);
6192         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6193         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6194         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6195         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6196         let htlc_minimum_msat: u64;
6197         {
6198                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6199                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6200                 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6201                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6202         }
6203
6204         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6205         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6206                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6207         check_added_monitors!(nodes[0], 1);
6208         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6209         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6210         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6211         assert!(nodes[1].node.list_channels().is_empty());
6212         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6213         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()));
6214         check_added_monitors!(nodes[1], 1);
6215         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6216 }
6217
6218 #[test]
6219 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6220         //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
6221         let chanmon_cfgs = create_chanmon_cfgs(2);
6222         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6223         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6224         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6225         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6226
6227         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6228         let channel_reserve = chan_stat.channel_reserve_msat;
6229         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6230         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
6231         // The 2* and +1 are for the fee spike reserve.
6232         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6233
6234         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6235         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6236         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6237                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6238         check_added_monitors!(nodes[0], 1);
6239         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6240
6241         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6242         // at this time channel-initiatee receivers are not required to enforce that senders
6243         // respect the fee_spike_reserve.
6244         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6245         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6246
6247         assert!(nodes[1].node.list_channels().is_empty());
6248         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6249         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6250         check_added_monitors!(nodes[1], 1);
6251         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6252 }
6253
6254 #[test]
6255 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6256         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6257         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6258         let chanmon_cfgs = create_chanmon_cfgs(2);
6259         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6260         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6261         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6262         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6263
6264         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6265         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6266         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6267         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6268         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6269                 &route.paths[0], 3999999, RecipientOnionFields::secret_only(our_payment_secret), cur_height, &None).unwrap();
6270         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6271
6272         let mut msg = msgs::UpdateAddHTLC {
6273                 channel_id: chan.2,
6274                 htlc_id: 0,
6275                 amount_msat: 1000,
6276                 payment_hash: our_payment_hash,
6277                 cltv_expiry: htlc_cltv,
6278                 onion_routing_packet: onion_packet.clone(),
6279         };
6280
6281         for i in 0..super::channel::OUR_MAX_HTLCS {
6282                 msg.htlc_id = i as u64;
6283                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6284         }
6285         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6286         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6287
6288         assert!(nodes[1].node.list_channels().is_empty());
6289         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6290         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6291         check_added_monitors!(nodes[1], 1);
6292         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6293 }
6294
6295 #[test]
6296 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6297         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6298         let chanmon_cfgs = create_chanmon_cfgs(2);
6299         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6300         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6301         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6302         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6303
6304         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6305         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6306                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6307         check_added_monitors!(nodes[0], 1);
6308         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6309         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;
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("Remote HTLC add would put them over our max HTLC value").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_add_htlc_bolt2_receiver_check_cltv_expiry() {
6321         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6322         let chanmon_cfgs = create_chanmon_cfgs(2);
6323         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6324         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6325         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6326
6327         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6328         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6329         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6330                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6331         check_added_monitors!(nodes[0], 1);
6332         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6333         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6334         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6335
6336         assert!(nodes[1].node.list_channels().is_empty());
6337         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6338         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6339         check_added_monitors!(nodes[1], 1);
6340         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6341 }
6342
6343 #[test]
6344 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6345         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6346         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6347         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6348         let chanmon_cfgs = create_chanmon_cfgs(2);
6349         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6350         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6351         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6352
6353         create_announced_chan_between_nodes(&nodes, 0, 1);
6354         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6355         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6356                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6357         check_added_monitors!(nodes[0], 1);
6358         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6359         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6360
6361         //Disconnect and Reconnect
6362         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6363         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6364         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();
6365         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6366         assert_eq!(reestablish_1.len(), 1);
6367         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();
6368         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6369         assert_eq!(reestablish_2.len(), 1);
6370         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6371         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6372         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6373         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6374
6375         //Resend HTLC
6376         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6377         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6378         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6379         check_added_monitors!(nodes[1], 1);
6380         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6381
6382         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6383
6384         assert!(nodes[1].node.list_channels().is_empty());
6385         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6386         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6387         check_added_monitors!(nodes[1], 1);
6388         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6389 }
6390
6391 #[test]
6392 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6393         //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.
6394
6395         let chanmon_cfgs = create_chanmon_cfgs(2);
6396         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6397         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6398         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6399         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6400         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6401         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6402                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6403
6404         check_added_monitors!(nodes[0], 1);
6405         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6406         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6407
6408         let update_msg = msgs::UpdateFulfillHTLC{
6409                 channel_id: chan.2,
6410                 htlc_id: 0,
6411                 payment_preimage: our_payment_preimage,
6412         };
6413
6414         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6415
6416         assert!(nodes[0].node.list_channels().is_empty());
6417         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6418         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()));
6419         check_added_monitors!(nodes[0], 1);
6420         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6421 }
6422
6423 #[test]
6424 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6425         //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.
6426
6427         let chanmon_cfgs = create_chanmon_cfgs(2);
6428         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6429         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6430         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6431         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6432
6433         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6434         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6435                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6436         check_added_monitors!(nodes[0], 1);
6437         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6438         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6439
6440         let update_msg = msgs::UpdateFailHTLC{
6441                 channel_id: chan.2,
6442                 htlc_id: 0,
6443                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6444         };
6445
6446         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6447
6448         assert!(nodes[0].node.list_channels().is_empty());
6449         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6450         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()));
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_update_fail_malformed_htlc_before_commitment() {
6457         //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.
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 mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6463         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6464
6465         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6466         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6467                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6468         check_added_monitors!(nodes[0], 1);
6469         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6470         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6471         let update_msg = msgs::UpdateFailMalformedHTLC{
6472                 channel_id: chan.2,
6473                 htlc_id: 0,
6474                 sha256_of_onion: [1; 32],
6475                 failure_code: 0x8000,
6476         };
6477
6478         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6479
6480         assert!(nodes[0].node.list_channels().is_empty());
6481         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6482         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()));
6483         check_added_monitors!(nodes[0], 1);
6484         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6485 }
6486
6487 #[test]
6488 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6489         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6490
6491         let chanmon_cfgs = create_chanmon_cfgs(2);
6492         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6493         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6494         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6495         create_announced_chan_between_nodes(&nodes, 0, 1);
6496
6497         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6498
6499         nodes[1].node.claim_funds(our_payment_preimage);
6500         check_added_monitors!(nodes[1], 1);
6501         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6502
6503         let events = nodes[1].node.get_and_clear_pending_msg_events();
6504         assert_eq!(events.len(), 1);
6505         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6506                 match events[0] {
6507                         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, .. } } => {
6508                                 assert!(update_add_htlcs.is_empty());
6509                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6510                                 assert!(update_fail_htlcs.is_empty());
6511                                 assert!(update_fail_malformed_htlcs.is_empty());
6512                                 assert!(update_fee.is_none());
6513                                 update_fulfill_htlcs[0].clone()
6514                         },
6515                         _ => panic!("Unexpected event"),
6516                 }
6517         };
6518
6519         update_fulfill_msg.htlc_id = 1;
6520
6521         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6522
6523         assert!(nodes[0].node.list_channels().is_empty());
6524         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6525         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6526         check_added_monitors!(nodes[0], 1);
6527         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6528 }
6529
6530 #[test]
6531 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6532         //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.
6533
6534         let chanmon_cfgs = create_chanmon_cfgs(2);
6535         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6536         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6537         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6538         create_announced_chan_between_nodes(&nodes, 0, 1);
6539
6540         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6541
6542         nodes[1].node.claim_funds(our_payment_preimage);
6543         check_added_monitors!(nodes[1], 1);
6544         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6545
6546         let events = nodes[1].node.get_and_clear_pending_msg_events();
6547         assert_eq!(events.len(), 1);
6548         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6549                 match events[0] {
6550                         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, .. } } => {
6551                                 assert!(update_add_htlcs.is_empty());
6552                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6553                                 assert!(update_fail_htlcs.is_empty());
6554                                 assert!(update_fail_malformed_htlcs.is_empty());
6555                                 assert!(update_fee.is_none());
6556                                 update_fulfill_htlcs[0].clone()
6557                         },
6558                         _ => panic!("Unexpected event"),
6559                 }
6560         };
6561
6562         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6563
6564         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6565
6566         assert!(nodes[0].node.list_channels().is_empty());
6567         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6568         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6569         check_added_monitors!(nodes[0], 1);
6570         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6571 }
6572
6573 #[test]
6574 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6575         //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.
6576
6577         let chanmon_cfgs = create_chanmon_cfgs(2);
6578         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6579         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6580         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6581         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6582
6583         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6584         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6585                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6586         check_added_monitors!(nodes[0], 1);
6587
6588         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6589         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6590
6591         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6592         check_added_monitors!(nodes[1], 0);
6593         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6594
6595         let events = nodes[1].node.get_and_clear_pending_msg_events();
6596
6597         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6598                 match events[0] {
6599                         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, .. } } => {
6600                                 assert!(update_add_htlcs.is_empty());
6601                                 assert!(update_fulfill_htlcs.is_empty());
6602                                 assert!(update_fail_htlcs.is_empty());
6603                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6604                                 assert!(update_fee.is_none());
6605                                 update_fail_malformed_htlcs[0].clone()
6606                         },
6607                         _ => panic!("Unexpected event"),
6608                 }
6609         };
6610         update_msg.failure_code &= !0x8000;
6611         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6612
6613         assert!(nodes[0].node.list_channels().is_empty());
6614         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6615         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6616         check_added_monitors!(nodes[0], 1);
6617         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6618 }
6619
6620 #[test]
6621 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6622         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6623         //    * 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.
6624
6625         let chanmon_cfgs = create_chanmon_cfgs(3);
6626         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6627         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6628         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6629         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6630         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6631
6632         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6633
6634         //First hop
6635         let mut payment_event = {
6636                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6637                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6638                 check_added_monitors!(nodes[0], 1);
6639                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6640                 assert_eq!(events.len(), 1);
6641                 SendEvent::from_event(events.remove(0))
6642         };
6643         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6644         check_added_monitors!(nodes[1], 0);
6645         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6646         expect_pending_htlcs_forwardable!(nodes[1]);
6647         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6648         assert_eq!(events_2.len(), 1);
6649         check_added_monitors!(nodes[1], 1);
6650         payment_event = SendEvent::from_event(events_2.remove(0));
6651         assert_eq!(payment_event.msgs.len(), 1);
6652
6653         //Second Hop
6654         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6655         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6656         check_added_monitors!(nodes[2], 0);
6657         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6658
6659         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6660         assert_eq!(events_3.len(), 1);
6661         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6662                 match events_3[0] {
6663                         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 } } => {
6664                                 assert!(update_add_htlcs.is_empty());
6665                                 assert!(update_fulfill_htlcs.is_empty());
6666                                 assert!(update_fail_htlcs.is_empty());
6667                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6668                                 assert!(update_fee.is_none());
6669                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6670                         },
6671                         _ => panic!("Unexpected event"),
6672                 }
6673         };
6674
6675         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6676
6677         check_added_monitors!(nodes[1], 0);
6678         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6679         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 }]);
6680         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6681         assert_eq!(events_4.len(), 1);
6682
6683         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6684         match events_4[0] {
6685                 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, .. } } => {
6686                         assert!(update_add_htlcs.is_empty());
6687                         assert!(update_fulfill_htlcs.is_empty());
6688                         assert_eq!(update_fail_htlcs.len(), 1);
6689                         assert!(update_fail_malformed_htlcs.is_empty());
6690                         assert!(update_fee.is_none());
6691                 },
6692                 _ => panic!("Unexpected event"),
6693         };
6694
6695         check_added_monitors!(nodes[1], 1);
6696 }
6697
6698 #[test]
6699 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6700         let chanmon_cfgs = create_chanmon_cfgs(3);
6701         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6702         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6703         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6704         create_announced_chan_between_nodes(&nodes, 0, 1);
6705         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6706
6707         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6708
6709         // First hop
6710         let mut payment_event = {
6711                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6712                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6713                 check_added_monitors!(nodes[0], 1);
6714                 SendEvent::from_node(&nodes[0])
6715         };
6716
6717         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6718         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6719         expect_pending_htlcs_forwardable!(nodes[1]);
6720         check_added_monitors!(nodes[1], 1);
6721         payment_event = SendEvent::from_node(&nodes[1]);
6722         assert_eq!(payment_event.msgs.len(), 1);
6723
6724         // Second Hop
6725         payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6726         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6727         check_added_monitors!(nodes[2], 0);
6728         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6729
6730         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6731         assert_eq!(events_3.len(), 1);
6732         match events_3[0] {
6733                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6734                         let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6735                         // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6736                         update_msg.failure_code |= 0x2000;
6737
6738                         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6739                         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6740                 },
6741                 _ => panic!("Unexpected event"),
6742         }
6743
6744         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6745                 vec![HTLCDestination::NextHopChannel {
6746                         node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6747         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6748         assert_eq!(events_4.len(), 1);
6749         check_added_monitors!(nodes[1], 1);
6750
6751         match events_4[0] {
6752                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6753                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6754                         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6755                 },
6756                 _ => panic!("Unexpected event"),
6757         }
6758
6759         let events_5 = nodes[0].node.get_and_clear_pending_events();
6760         assert_eq!(events_5.len(), 2);
6761
6762         // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6763         // the node originating the error to its next hop.
6764         match events_5[0] {
6765                 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6766                 } => {
6767                         assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6768                         assert!(is_permanent);
6769                         assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6770                 },
6771                 _ => panic!("Unexpected event"),
6772         }
6773         match events_5[1] {
6774                 Event::PaymentFailed { payment_hash, .. } => {
6775                         assert_eq!(payment_hash, our_payment_hash);
6776                 },
6777                 _ => panic!("Unexpected event"),
6778         }
6779
6780         // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6781 }
6782
6783 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6784         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6785         // 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
6786         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6787
6788         let mut chanmon_cfgs = create_chanmon_cfgs(2);
6789         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6790         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6791         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6792         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6793         let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
6794
6795         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6796                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6797
6798         // We route 2 dust-HTLCs between A and B
6799         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6800         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6801         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6802
6803         // Cache one local commitment tx as previous
6804         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6805
6806         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6807         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6808         check_added_monitors!(nodes[1], 0);
6809         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6810         check_added_monitors!(nodes[1], 1);
6811
6812         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6813         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6814         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6815         check_added_monitors!(nodes[0], 1);
6816
6817         // Cache one local commitment tx as lastest
6818         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6819
6820         let events = nodes[0].node.get_and_clear_pending_msg_events();
6821         match events[0] {
6822                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6823                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6824                 },
6825                 _ => panic!("Unexpected event"),
6826         }
6827         match events[1] {
6828                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6829                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6830                 },
6831                 _ => panic!("Unexpected event"),
6832         }
6833
6834         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6835         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6836         if announce_latest {
6837                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6838         } else {
6839                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6840         }
6841
6842         check_closed_broadcast!(nodes[0], true);
6843         check_added_monitors!(nodes[0], 1);
6844         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6845
6846         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6847         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6848         let events = nodes[0].node.get_and_clear_pending_events();
6849         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6850         assert_eq!(events.len(), 4);
6851         let mut first_failed = false;
6852         for event in events {
6853                 match event {
6854                         Event::PaymentPathFailed { payment_hash, .. } => {
6855                                 if payment_hash == payment_hash_1 {
6856                                         assert!(!first_failed);
6857                                         first_failed = true;
6858                                 } else {
6859                                         assert_eq!(payment_hash, payment_hash_2);
6860                                 }
6861                         },
6862                         Event::PaymentFailed { .. } => {}
6863                         _ => panic!("Unexpected event"),
6864                 }
6865         }
6866 }
6867
6868 #[test]
6869 fn test_failure_delay_dust_htlc_local_commitment() {
6870         do_test_failure_delay_dust_htlc_local_commitment(true);
6871         do_test_failure_delay_dust_htlc_local_commitment(false);
6872 }
6873
6874 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6875         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6876         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6877         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6878         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6879         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6880         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6881
6882         let chanmon_cfgs = create_chanmon_cfgs(3);
6883         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6884         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6885         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6886         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6887
6888         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6889                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6890
6891         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6892         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6893
6894         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6895         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6896
6897         // We revoked bs_commitment_tx
6898         if revoked {
6899                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6900                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6901         }
6902
6903         let mut timeout_tx = Vec::new();
6904         if local {
6905                 // We fail dust-HTLC 1 by broadcast of local commitment tx
6906                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
6907                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6908                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6909                 expect_payment_failed!(nodes[0], dust_hash, false);
6910
6911                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
6912                 check_closed_broadcast!(nodes[0], true);
6913                 check_added_monitors!(nodes[0], 1);
6914                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6915                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6916                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6917                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6918                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6919                 mine_transaction(&nodes[0], &timeout_tx[0]);
6920                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6921                 expect_payment_failed!(nodes[0], non_dust_hash, false);
6922         } else {
6923                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6924                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
6925                 check_closed_broadcast!(nodes[0], true);
6926                 check_added_monitors!(nodes[0], 1);
6927                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6928                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6929
6930                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
6931                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
6932                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
6933                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
6934                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
6935                 // dust HTLC should have been failed.
6936                 expect_payment_failed!(nodes[0], dust_hash, false);
6937
6938                 if !revoked {
6939                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6940                 } else {
6941                         assert_eq!(timeout_tx[0].lock_time.0, 12);
6942                 }
6943                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
6944                 mine_transaction(&nodes[0], &timeout_tx[0]);
6945                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6946                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6947                 expect_payment_failed!(nodes[0], non_dust_hash, false);
6948         }
6949 }
6950
6951 #[test]
6952 fn test_sweep_outbound_htlc_failure_update() {
6953         do_test_sweep_outbound_htlc_failure_update(false, true);
6954         do_test_sweep_outbound_htlc_failure_update(false, false);
6955         do_test_sweep_outbound_htlc_failure_update(true, false);
6956 }
6957
6958 #[test]
6959 fn test_user_configurable_csv_delay() {
6960         // We test our channel constructors yield errors when we pass them absurd csv delay
6961
6962         let mut low_our_to_self_config = UserConfig::default();
6963         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
6964         let mut high_their_to_self_config = UserConfig::default();
6965         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
6966         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6967         let chanmon_cfgs = create_chanmon_cfgs(2);
6968         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6969         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6970         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6971
6972         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6973         if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6974                 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
6975                 &low_our_to_self_config, 0, 42)
6976         {
6977                 match error {
6978                         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())); },
6979                         _ => panic!("Unexpected event"),
6980                 }
6981         } else { assert!(false) }
6982
6983         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6984         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6985         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6986         open_channel.to_self_delay = 200;
6987         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6988                 &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,
6989                 &low_our_to_self_config, 0, &nodes[0].logger, 42)
6990         {
6991                 match error {
6992                         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()));  },
6993                         _ => panic!("Unexpected event"),
6994                 }
6995         } else { assert!(false); }
6996
6997         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6998         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6999         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()));
7000         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7001         accept_channel.to_self_delay = 200;
7002         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
7003         let reason_msg;
7004         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7005                 match action {
7006                         &ErrorAction::SendErrorMessage { ref msg } => {
7007                                 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()));
7008                                 reason_msg = msg.data.clone();
7009                         },
7010                         _ => { panic!(); }
7011                 }
7012         } else { panic!(); }
7013         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7014
7015         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7016         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7017         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7018         open_channel.to_self_delay = 200;
7019         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7020                 &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,
7021                 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7022         {
7023                 match error {
7024                         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())); },
7025                         _ => panic!("Unexpected event"),
7026                 }
7027         } else { assert!(false); }
7028 }
7029
7030 #[test]
7031 fn test_check_htlc_underpaying() {
7032         // Send payment through A -> B but A is maliciously
7033         // sending a probe payment (i.e less than expected value0
7034         // to B, B should refuse payment.
7035
7036         let chanmon_cfgs = create_chanmon_cfgs(2);
7037         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7038         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7039         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7040
7041         // Create some initial channels
7042         create_announced_chan_between_nodes(&nodes, 0, 1);
7043
7044         let scorer = test_utils::TestScorer::new();
7045         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7046         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV).with_features(nodes[1].node.invoice_features());
7047         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();
7048         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7049         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7050         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7051                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7052         check_added_monitors!(nodes[0], 1);
7053
7054         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7055         assert_eq!(events.len(), 1);
7056         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7057         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7058         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7059
7060         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7061         // and then will wait a second random delay before failing the HTLC back:
7062         expect_pending_htlcs_forwardable!(nodes[1]);
7063         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7064
7065         // Node 3 is expecting payment of 100_000 but received 10_000,
7066         // it should fail htlc like we didn't know the preimage.
7067         nodes[1].node.process_pending_htlc_forwards();
7068
7069         let events = nodes[1].node.get_and_clear_pending_msg_events();
7070         assert_eq!(events.len(), 1);
7071         let (update_fail_htlc, commitment_signed) = match events[0] {
7072                 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 } } => {
7073                         assert!(update_add_htlcs.is_empty());
7074                         assert!(update_fulfill_htlcs.is_empty());
7075                         assert_eq!(update_fail_htlcs.len(), 1);
7076                         assert!(update_fail_malformed_htlcs.is_empty());
7077                         assert!(update_fee.is_none());
7078                         (update_fail_htlcs[0].clone(), commitment_signed)
7079                 },
7080                 _ => panic!("Unexpected event"),
7081         };
7082         check_added_monitors!(nodes[1], 1);
7083
7084         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7085         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7086
7087         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7088         let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7089         expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7090         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7091 }
7092
7093 #[test]
7094 fn test_announce_disable_channels() {
7095         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7096         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7097
7098         let chanmon_cfgs = create_chanmon_cfgs(2);
7099         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7100         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7101         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7102
7103         create_announced_chan_between_nodes(&nodes, 0, 1);
7104         create_announced_chan_between_nodes(&nodes, 1, 0);
7105         create_announced_chan_between_nodes(&nodes, 0, 1);
7106
7107         // Disconnect peers
7108         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7109         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7110
7111         nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7112         nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7113         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7114         assert_eq!(msg_events.len(), 3);
7115         let mut chans_disabled = HashMap::new();
7116         for e in msg_events {
7117                 match e {
7118                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7119                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7120                                 // Check that each channel gets updated exactly once
7121                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7122                                         panic!("Generated ChannelUpdate for wrong chan!");
7123                                 }
7124                         },
7125                         _ => panic!("Unexpected event"),
7126                 }
7127         }
7128         // Reconnect peers
7129         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();
7130         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7131         assert_eq!(reestablish_1.len(), 3);
7132         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();
7133         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7134         assert_eq!(reestablish_2.len(), 3);
7135
7136         // Reestablish chan_1
7137         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7138         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7139         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7140         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7141         // Reestablish chan_2
7142         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7143         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7144         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7145         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7146         // Reestablish chan_3
7147         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7148         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7149         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7150         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7151
7152         nodes[0].node.timer_tick_occurred();
7153         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7154         nodes[0].node.timer_tick_occurred();
7155         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7156         assert_eq!(msg_events.len(), 3);
7157         for e in msg_events {
7158                 match e {
7159                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7160                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7161                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7162                                         // Each update should have a higher timestamp than the previous one, replacing
7163                                         // the old one.
7164                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7165                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7166                                 }
7167                         },
7168                         _ => panic!("Unexpected event"),
7169                 }
7170         }
7171         // Check that each channel gets updated exactly once
7172         assert!(chans_disabled.is_empty());
7173 }
7174
7175 #[test]
7176 fn test_bump_penalty_txn_on_revoked_commitment() {
7177         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7178         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7179
7180         let chanmon_cfgs = create_chanmon_cfgs(2);
7181         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7182         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7183         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7184
7185         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7186
7187         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7188         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7189                 .with_features(nodes[0].node.invoice_features());
7190         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7191         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7192
7193         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7194         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7195         assert_eq!(revoked_txn[0].output.len(), 4);
7196         assert_eq!(revoked_txn[0].input.len(), 1);
7197         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7198         let revoked_txid = revoked_txn[0].txid();
7199
7200         let mut penalty_sum = 0;
7201         for outp in revoked_txn[0].output.iter() {
7202                 if outp.script_pubkey.is_v0_p2wsh() {
7203                         penalty_sum += outp.value;
7204                 }
7205         }
7206
7207         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7208         let header_114 = connect_blocks(&nodes[1], 14);
7209
7210         // Actually revoke tx by claiming a HTLC
7211         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7212         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7213         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7214         check_added_monitors!(nodes[1], 1);
7215
7216         // One or more justice tx should have been broadcast, check it
7217         let penalty_1;
7218         let feerate_1;
7219         {
7220                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7221                 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7222                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7223                 assert_eq!(node_txn[0].output.len(), 1);
7224                 check_spends!(node_txn[0], revoked_txn[0]);
7225                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7226                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7227                 penalty_1 = node_txn[0].txid();
7228                 node_txn.clear();
7229         };
7230
7231         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7232         connect_blocks(&nodes[1], 15);
7233         let mut penalty_2 = penalty_1;
7234         let mut feerate_2 = 0;
7235         {
7236                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7237                 assert_eq!(node_txn.len(), 1);
7238                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7239                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7240                         assert_eq!(node_txn[0].output.len(), 1);
7241                         check_spends!(node_txn[0], revoked_txn[0]);
7242                         penalty_2 = node_txn[0].txid();
7243                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7244                         assert_ne!(penalty_2, penalty_1);
7245                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7246                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7247                         // Verify 25% bump heuristic
7248                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7249                         node_txn.clear();
7250                 }
7251         }
7252         assert_ne!(feerate_2, 0);
7253
7254         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7255         connect_blocks(&nodes[1], 1);
7256         let penalty_3;
7257         let mut feerate_3 = 0;
7258         {
7259                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7260                 assert_eq!(node_txn.len(), 1);
7261                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7262                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7263                         assert_eq!(node_txn[0].output.len(), 1);
7264                         check_spends!(node_txn[0], revoked_txn[0]);
7265                         penalty_3 = node_txn[0].txid();
7266                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7267                         assert_ne!(penalty_3, penalty_2);
7268                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7269                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7270                         // Verify 25% bump heuristic
7271                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7272                         node_txn.clear();
7273                 }
7274         }
7275         assert_ne!(feerate_3, 0);
7276
7277         nodes[1].node.get_and_clear_pending_events();
7278         nodes[1].node.get_and_clear_pending_msg_events();
7279 }
7280
7281 #[test]
7282 fn test_bump_penalty_txn_on_revoked_htlcs() {
7283         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7284         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7285
7286         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7287         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7288         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7289         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7290         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7291
7292         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7293         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7294         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_features(nodes[1].node.invoice_features());
7295         let scorer = test_utils::TestScorer::new();
7296         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7297         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7298                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7299         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7300         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_features(nodes[0].node.invoice_features());
7301         let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7302                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7303         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7304
7305         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7306         assert_eq!(revoked_local_txn[0].input.len(), 1);
7307         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7308
7309         // Revoke local commitment tx
7310         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7311
7312         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7313         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7314         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7315         check_closed_broadcast!(nodes[1], true);
7316         check_added_monitors!(nodes[1], 1);
7317         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7318         connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7319
7320         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
7321         assert_eq!(revoked_htlc_txn.len(), 2);
7322
7323         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7324         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7325         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7326
7327         assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7328         assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7329         assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7330         check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7331
7332         // Broadcast set of revoked txn on A
7333         let hash_128 = connect_blocks(&nodes[0], 40);
7334         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7335         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7336         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7337         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] });
7338         let events = nodes[0].node.get_and_clear_pending_events();
7339         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7340         match events.last().unwrap() {
7341                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7342                 _ => panic!("Unexpected event"),
7343         }
7344         let first;
7345         let feerate_1;
7346         let penalty_txn;
7347         {
7348                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7349                 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7350                 // Verify claim tx are spending revoked HTLC txn
7351
7352                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7353                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7354                 // which are included in the same block (they are broadcasted because we scan the
7355                 // transactions linearly and generate claims as we go, they likely should be removed in the
7356                 // future).
7357                 assert_eq!(node_txn[0].input.len(), 1);
7358                 check_spends!(node_txn[0], revoked_local_txn[0]);
7359                 assert_eq!(node_txn[1].input.len(), 1);
7360                 check_spends!(node_txn[1], revoked_local_txn[0]);
7361                 assert_eq!(node_txn[2].input.len(), 1);
7362                 check_spends!(node_txn[2], revoked_local_txn[0]);
7363
7364                 // Each of the three justice transactions claim a separate (single) output of the three
7365                 // available, which we check here:
7366                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7367                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7368                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7369
7370                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7371                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7372
7373                 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7374                 // output, checked above).
7375                 assert_eq!(node_txn[3].input.len(), 2);
7376                 assert_eq!(node_txn[3].output.len(), 1);
7377                 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7378
7379                 first = node_txn[3].txid();
7380                 // Store both feerates for later comparison
7381                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7382                 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7383                 penalty_txn = vec![node_txn[2].clone()];
7384                 node_txn.clear();
7385         }
7386
7387         // Connect one more block to see if bumped penalty are issued for HTLC txn
7388         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7389         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7390         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7391         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7392
7393         // Few more blocks to confirm penalty txn
7394         connect_blocks(&nodes[0], 4);
7395         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7396         let header_144 = connect_blocks(&nodes[0], 9);
7397         let node_txn = {
7398                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7399                 assert_eq!(node_txn.len(), 1);
7400
7401                 assert_eq!(node_txn[0].input.len(), 2);
7402                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7403                 // Verify bumped tx is different and 25% bump heuristic
7404                 assert_ne!(first, node_txn[0].txid());
7405                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7406                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7407                 assert!(feerate_2 * 100 > feerate_1 * 125);
7408                 let txn = vec![node_txn[0].clone()];
7409                 node_txn.clear();
7410                 txn
7411         };
7412         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7413         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7414         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7415         connect_blocks(&nodes[0], 20);
7416         {
7417                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7418                 // We verify than no new transaction has been broadcast because previously
7419                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7420                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7421                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7422                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7423                 // up bumped justice generation.
7424                 assert_eq!(node_txn.len(), 0);
7425                 node_txn.clear();
7426         }
7427         check_closed_broadcast!(nodes[0], true);
7428         check_added_monitors!(nodes[0], 1);
7429 }
7430
7431 #[test]
7432 fn test_bump_penalty_txn_on_remote_commitment() {
7433         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7434         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7435
7436         // Create 2 HTLCs
7437         // Provide preimage for one
7438         // Check aggregation
7439
7440         let chanmon_cfgs = create_chanmon_cfgs(2);
7441         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7442         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7443         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7444
7445         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7446         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7447         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7448
7449         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7450         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7451         assert_eq!(remote_txn[0].output.len(), 4);
7452         assert_eq!(remote_txn[0].input.len(), 1);
7453         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7454
7455         // Claim a HTLC without revocation (provide B monitor with preimage)
7456         nodes[1].node.claim_funds(payment_preimage);
7457         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7458         mine_transaction(&nodes[1], &remote_txn[0]);
7459         check_added_monitors!(nodes[1], 2);
7460         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7461
7462         // One or more claim tx should have been broadcast, check it
7463         let timeout;
7464         let preimage;
7465         let preimage_bump;
7466         let feerate_timeout;
7467         let feerate_preimage;
7468         {
7469                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7470                 // 3 transactions including:
7471                 //   preimage and timeout sweeps from remote commitment + preimage sweep bump
7472                 assert_eq!(node_txn.len(), 3);
7473                 assert_eq!(node_txn[0].input.len(), 1);
7474                 assert_eq!(node_txn[1].input.len(), 1);
7475                 assert_eq!(node_txn[2].input.len(), 1);
7476                 check_spends!(node_txn[0], remote_txn[0]);
7477                 check_spends!(node_txn[1], remote_txn[0]);
7478                 check_spends!(node_txn[2], remote_txn[0]);
7479
7480                 preimage = node_txn[0].txid();
7481                 let index = node_txn[0].input[0].previous_output.vout;
7482                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7483                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7484
7485                 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7486                         (node_txn[2].clone(), node_txn[1].clone())
7487                 } else {
7488                         (node_txn[1].clone(), node_txn[2].clone())
7489                 };
7490
7491                 preimage_bump = preimage_bump_tx;
7492                 check_spends!(preimage_bump, remote_txn[0]);
7493                 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7494
7495                 timeout = timeout_tx.txid();
7496                 let index = timeout_tx.input[0].previous_output.vout;
7497                 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7498                 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7499
7500                 node_txn.clear();
7501         };
7502         assert_ne!(feerate_timeout, 0);
7503         assert_ne!(feerate_preimage, 0);
7504
7505         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7506         connect_blocks(&nodes[1], 15);
7507         {
7508                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7509                 assert_eq!(node_txn.len(), 1);
7510                 assert_eq!(node_txn[0].input.len(), 1);
7511                 assert_eq!(preimage_bump.input.len(), 1);
7512                 check_spends!(node_txn[0], remote_txn[0]);
7513                 check_spends!(preimage_bump, remote_txn[0]);
7514
7515                 let index = preimage_bump.input[0].previous_output.vout;
7516                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7517                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7518                 assert!(new_feerate * 100 > feerate_timeout * 125);
7519                 assert_ne!(timeout, preimage_bump.txid());
7520
7521                 let index = node_txn[0].input[0].previous_output.vout;
7522                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7523                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7524                 assert!(new_feerate * 100 > feerate_preimage * 125);
7525                 assert_ne!(preimage, node_txn[0].txid());
7526
7527                 node_txn.clear();
7528         }
7529
7530         nodes[1].node.get_and_clear_pending_events();
7531         nodes[1].node.get_and_clear_pending_msg_events();
7532 }
7533
7534 #[test]
7535 fn test_counterparty_raa_skip_no_crash() {
7536         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7537         // commitment transaction, we would have happily carried on and provided them the next
7538         // commitment transaction based on one RAA forward. This would probably eventually have led to
7539         // channel closure, but it would not have resulted in funds loss. Still, our
7540         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7541         // check simply that the channel is closed in response to such an RAA, but don't check whether
7542         // we decide to punish our counterparty for revoking their funds (as we don't currently
7543         // implement that).
7544         let chanmon_cfgs = create_chanmon_cfgs(2);
7545         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7546         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7547         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7548         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7549
7550         let per_commitment_secret;
7551         let next_per_commitment_point;
7552         {
7553                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7554                 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7555                 let keys = guard.channel_by_id.get_mut(&channel_id).unwrap().get_signer();
7556
7557                 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7558
7559                 // Make signer believe we got a counterparty signature, so that it allows the revocation
7560                 keys.get_enforcement_state().last_holder_commitment -= 1;
7561                 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7562
7563                 // Must revoke without gaps
7564                 keys.get_enforcement_state().last_holder_commitment -= 1;
7565                 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7566
7567                 keys.get_enforcement_state().last_holder_commitment -= 1;
7568                 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7569                         &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7570         }
7571
7572         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7573                 &msgs::RevokeAndACK {
7574                         channel_id,
7575                         per_commitment_secret,
7576                         next_per_commitment_point,
7577                         #[cfg(taproot)]
7578                         next_local_nonce: None,
7579                 });
7580         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7581         check_added_monitors!(nodes[1], 1);
7582         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7583 }
7584
7585 #[test]
7586 fn test_bump_txn_sanitize_tracking_maps() {
7587         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7588         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7589
7590         let chanmon_cfgs = create_chanmon_cfgs(2);
7591         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7592         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7593         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7594
7595         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7596         // Lock HTLC in both directions
7597         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7598         let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7599
7600         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7601         assert_eq!(revoked_local_txn[0].input.len(), 1);
7602         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7603
7604         // Revoke local commitment tx
7605         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7606
7607         // Broadcast set of revoked txn on A
7608         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7609         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7610         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7611
7612         mine_transaction(&nodes[0], &revoked_local_txn[0]);
7613         check_closed_broadcast!(nodes[0], true);
7614         check_added_monitors!(nodes[0], 1);
7615         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7616         let penalty_txn = {
7617                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7618                 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7619                 check_spends!(node_txn[0], revoked_local_txn[0]);
7620                 check_spends!(node_txn[1], revoked_local_txn[0]);
7621                 check_spends!(node_txn[2], revoked_local_txn[0]);
7622                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7623                 node_txn.clear();
7624                 penalty_txn
7625         };
7626         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7627         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7628         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7629         {
7630                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7631                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7632                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7633         }
7634 }
7635
7636 #[test]
7637 fn test_pending_claimed_htlc_no_balance_underflow() {
7638         // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
7639         // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
7640         let chanmon_cfgs = create_chanmon_cfgs(2);
7641         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7642         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7643         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7644         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
7645
7646         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
7647         nodes[1].node.claim_funds(payment_preimage);
7648         expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
7649         check_added_monitors!(nodes[1], 1);
7650         let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7651
7652         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
7653         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
7654         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
7655         check_added_monitors!(nodes[0], 1);
7656         let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7657
7658         // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
7659         // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
7660         // can get our balance.
7661
7662         // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
7663         // the public key of the only hop. This works around ChannelDetails not showing the
7664         // almost-claimed HTLC as available balance.
7665         let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
7666         route.payment_params = None; // This is all wrong, but unnecessary
7667         route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
7668         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
7669         nodes[1].node.send_payment_with_route(&route, payment_hash_2,
7670                 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
7671
7672         assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
7673 }
7674
7675 #[test]
7676 fn test_channel_conf_timeout() {
7677         // Tests that, for inbound channels, we give up on them if the funding transaction does not
7678         // confirm within 2016 blocks, as recommended by BOLT 2.
7679         let chanmon_cfgs = create_chanmon_cfgs(2);
7680         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7681         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7682         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7683
7684         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7685
7686         // The outbound node should wait forever for confirmation:
7687         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7688         // copied here instead of directly referencing the constant.
7689         connect_blocks(&nodes[0], 2016);
7690         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7691
7692         // The inbound node should fail the channel after exactly 2016 blocks
7693         connect_blocks(&nodes[1], 2015);
7694         check_added_monitors!(nodes[1], 0);
7695         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7696
7697         connect_blocks(&nodes[1], 1);
7698         check_added_monitors!(nodes[1], 1);
7699         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
7700         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7701         assert_eq!(close_ev.len(), 1);
7702         match close_ev[0] {
7703                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7704                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7705                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7706                 },
7707                 _ => panic!("Unexpected event"),
7708         }
7709 }
7710
7711 #[test]
7712 fn test_override_channel_config() {
7713         let chanmon_cfgs = create_chanmon_cfgs(2);
7714         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7715         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7716         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7717
7718         // Node0 initiates a channel to node1 using the override config.
7719         let mut override_config = UserConfig::default();
7720         override_config.channel_handshake_config.our_to_self_delay = 200;
7721
7722         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7723
7724         // Assert the channel created by node0 is using the override config.
7725         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7726         assert_eq!(res.channel_flags, 0);
7727         assert_eq!(res.to_self_delay, 200);
7728 }
7729
7730 #[test]
7731 fn test_override_0msat_htlc_minimum() {
7732         let mut zero_config = UserConfig::default();
7733         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7734         let chanmon_cfgs = create_chanmon_cfgs(2);
7735         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7736         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7737         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7738
7739         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7740         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7741         assert_eq!(res.htlc_minimum_msat, 1);
7742
7743         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7744         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7745         assert_eq!(res.htlc_minimum_msat, 1);
7746 }
7747
7748 #[test]
7749 fn test_channel_update_has_correct_htlc_maximum_msat() {
7750         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7751         // Bolt 7 specifies that if present `htlc_maximum_msat`:
7752         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7753         // 90% of the `channel_value`.
7754         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7755
7756         let mut config_30_percent = UserConfig::default();
7757         config_30_percent.channel_handshake_config.announced_channel = true;
7758         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7759         let mut config_50_percent = UserConfig::default();
7760         config_50_percent.channel_handshake_config.announced_channel = true;
7761         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7762         let mut config_95_percent = UserConfig::default();
7763         config_95_percent.channel_handshake_config.announced_channel = true;
7764         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7765         let mut config_100_percent = UserConfig::default();
7766         config_100_percent.channel_handshake_config.announced_channel = true;
7767         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7768
7769         let chanmon_cfgs = create_chanmon_cfgs(4);
7770         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7771         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)]);
7772         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7773
7774         let channel_value_satoshis = 100000;
7775         let channel_value_msat = channel_value_satoshis * 1000;
7776         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7777         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7778         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7779
7780         let (node_0_chan_update, node_1_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7781         let (node_2_chan_update, node_3_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7782
7783         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7784         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7785         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7786         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7787         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7788         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7789
7790         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7791         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7792         // `channel_value`.
7793         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7794         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7795         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7796         // `channel_value`.
7797         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7798 }
7799
7800 #[test]
7801 fn test_manually_accept_inbound_channel_request() {
7802         let mut manually_accept_conf = UserConfig::default();
7803         manually_accept_conf.manually_accept_inbound_channels = true;
7804         let chanmon_cfgs = create_chanmon_cfgs(2);
7805         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7806         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7807         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7808
7809         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7810         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7811
7812         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7813
7814         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7815         // accepting the inbound channel request.
7816         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7817
7818         let events = nodes[1].node.get_and_clear_pending_events();
7819         match events[0] {
7820                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7821                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7822                 }
7823                 _ => panic!("Unexpected event"),
7824         }
7825
7826         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7827         assert_eq!(accept_msg_ev.len(), 1);
7828
7829         match accept_msg_ev[0] {
7830                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7831                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7832                 }
7833                 _ => panic!("Unexpected event"),
7834         }
7835
7836         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7837
7838         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7839         assert_eq!(close_msg_ev.len(), 1);
7840
7841         let events = nodes[1].node.get_and_clear_pending_events();
7842         match events[0] {
7843                 Event::ChannelClosed { user_channel_id, .. } => {
7844                         assert_eq!(user_channel_id, 23);
7845                 }
7846                 _ => panic!("Unexpected event"),
7847         }
7848 }
7849
7850 #[test]
7851 fn test_manually_reject_inbound_channel_request() {
7852         let mut manually_accept_conf = UserConfig::default();
7853         manually_accept_conf.manually_accept_inbound_channels = true;
7854         let chanmon_cfgs = create_chanmon_cfgs(2);
7855         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7856         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7857         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7858
7859         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7860         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7861
7862         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7863
7864         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7865         // rejecting the inbound channel request.
7866         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7867
7868         let events = nodes[1].node.get_and_clear_pending_events();
7869         match events[0] {
7870                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7871                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7872                 }
7873                 _ => panic!("Unexpected event"),
7874         }
7875
7876         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7877         assert_eq!(close_msg_ev.len(), 1);
7878
7879         match close_msg_ev[0] {
7880                 MessageSendEvent::HandleError { ref node_id, .. } => {
7881                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7882                 }
7883                 _ => panic!("Unexpected event"),
7884         }
7885         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
7886 }
7887
7888 #[test]
7889 fn test_reject_funding_before_inbound_channel_accepted() {
7890         // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
7891         // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
7892         // the node operator before the counterparty sends a `FundingCreated` message. If a
7893         // `FundingCreated` message is received before the channel is accepted, it should be rejected
7894         // and the channel should be closed.
7895         let mut manually_accept_conf = UserConfig::default();
7896         manually_accept_conf.manually_accept_inbound_channels = true;
7897         let chanmon_cfgs = create_chanmon_cfgs(2);
7898         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7899         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7900         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7901
7902         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7903         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7904         let temp_channel_id = res.temporary_channel_id;
7905
7906         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7907
7908         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
7909         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7910
7911         // Clear the `Event::OpenChannelRequest` event without responding to the request.
7912         nodes[1].node.get_and_clear_pending_events();
7913
7914         // Get the `AcceptChannel` message of `nodes[1]` without calling
7915         // `ChannelManager::accept_inbound_channel`, which generates a
7916         // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
7917         // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
7918         // succeed when `nodes[0]` is passed to it.
7919         let accept_chan_msg = {
7920                 let mut node_1_per_peer_lock;
7921                 let mut node_1_peer_state_lock;
7922                 let channel =  get_channel_ref!(&nodes[1], nodes[0], node_1_per_peer_lock, node_1_peer_state_lock, temp_channel_id);
7923                 channel.get_accept_channel_message()
7924         };
7925         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
7926
7927         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
7928
7929         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
7930         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
7931
7932         // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
7933         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
7934
7935         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7936         assert_eq!(close_msg_ev.len(), 1);
7937
7938         let expected_err = "FundingCreated message received before the channel was accepted";
7939         match close_msg_ev[0] {
7940                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
7941                         assert_eq!(msg.channel_id, temp_channel_id);
7942                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7943                         assert_eq!(msg.data, expected_err);
7944                 }
7945                 _ => panic!("Unexpected event"),
7946         }
7947
7948         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
7949 }
7950
7951 #[test]
7952 fn test_can_not_accept_inbound_channel_twice() {
7953         let mut manually_accept_conf = UserConfig::default();
7954         manually_accept_conf.manually_accept_inbound_channels = true;
7955         let chanmon_cfgs = create_chanmon_cfgs(2);
7956         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7957         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7958         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7959
7960         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7961         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7962
7963         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7964
7965         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7966         // accepting the inbound channel request.
7967         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7968
7969         let events = nodes[1].node.get_and_clear_pending_events();
7970         match events[0] {
7971                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7972                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7973                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7974                         match api_res {
7975                                 Err(APIError::APIMisuseError { err }) => {
7976                                         assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
7977                                 },
7978                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7979                                 Err(_) => panic!("Unexpected Error"),
7980                         }
7981                 }
7982                 _ => panic!("Unexpected event"),
7983         }
7984
7985         // Ensure that the channel wasn't closed after attempting to accept it twice.
7986         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7987         assert_eq!(accept_msg_ev.len(), 1);
7988
7989         match accept_msg_ev[0] {
7990                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7991                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7992                 }
7993                 _ => panic!("Unexpected event"),
7994         }
7995 }
7996
7997 #[test]
7998 fn test_can_not_accept_unknown_inbound_channel() {
7999         let chanmon_cfg = create_chanmon_cfgs(2);
8000         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8001         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8002         let nodes = create_network(2, &node_cfg, &node_chanmgr);
8003
8004         let unknown_channel_id = [0; 32];
8005         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8006         match api_res {
8007                 Err(APIError::ChannelUnavailable { err }) => {
8008                         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()));
8009                 },
8010                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8011                 Err(_) => panic!("Unexpected Error"),
8012         }
8013 }
8014
8015 #[test]
8016 fn test_onion_value_mpp_set_calculation() {
8017         // Test that we use the onion value `amt_to_forward` when
8018         // calculating whether we've reached the `total_msat` of an MPP
8019         // by having a routing node forward more than `amt_to_forward`
8020         // and checking that the receiving node doesn't generate
8021         // a PaymentClaimable event too early
8022         let node_count = 4;
8023         let chanmon_cfgs = create_chanmon_cfgs(node_count);
8024         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8025         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8026         let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8027
8028         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8029         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8030         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8031         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8032
8033         let total_msat = 100_000;
8034         let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
8035         let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
8036         let sample_path = route.paths.pop().unwrap();
8037
8038         let mut path_1 = sample_path.clone();
8039         path_1[0].pubkey = nodes[1].node.get_our_node_id();
8040         path_1[0].short_channel_id = chan_1_id;
8041         path_1[1].pubkey = nodes[3].node.get_our_node_id();
8042         path_1[1].short_channel_id = chan_3_id;
8043         path_1[1].fee_msat = 100_000;
8044         route.paths.push(path_1);
8045
8046         let mut path_2 = sample_path.clone();
8047         path_2[0].pubkey = nodes[2].node.get_our_node_id();
8048         path_2[0].short_channel_id = chan_2_id;
8049         path_2[1].pubkey = nodes[3].node.get_our_node_id();
8050         path_2[1].short_channel_id = chan_4_id;
8051         path_2[1].fee_msat = 1_000;
8052         route.paths.push(path_2);
8053
8054         // Send payment
8055         let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
8056         let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
8057                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8058         nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
8059                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8060         check_added_monitors!(nodes[0], expected_paths.len());
8061
8062         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8063         assert_eq!(events.len(), expected_paths.len());
8064
8065         // First path
8066         let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8067         let mut payment_event = SendEvent::from_event(ev);
8068         let mut prev_node = &nodes[0];
8069
8070         for (idx, &node) in expected_paths[0].iter().enumerate() {
8071                 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8072
8073                 if idx == 0 { // routing node
8074                         let session_priv = [3; 32];
8075                         let height = nodes[0].best_block_info().1;
8076                         let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8077                         let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8078                         let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8079                                 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8080                         // Edit amt_to_forward to simulate the sender having set
8081                         // the final amount and the routing node taking less fee
8082                         onion_payloads[1].amt_to_forward = 99_000;
8083                         let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
8084                         payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8085                 }
8086
8087                 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8088                 check_added_monitors!(node, 0);
8089                 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8090                 expect_pending_htlcs_forwardable!(node);
8091
8092                 if idx == 0 {
8093                         let mut events_2 = node.node.get_and_clear_pending_msg_events();
8094                         assert_eq!(events_2.len(), 1);
8095                         check_added_monitors!(node, 1);
8096                         payment_event = SendEvent::from_event(events_2.remove(0));
8097                         assert_eq!(payment_event.msgs.len(), 1);
8098                 } else {
8099                         let events_2 = node.node.get_and_clear_pending_events();
8100                         assert!(events_2.is_empty());
8101                 }
8102
8103                 prev_node = node;
8104         }
8105
8106         // Second path
8107         let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8108         pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8109
8110         claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8111 }
8112
8113 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8114
8115         let routing_node_count = msat_amounts.len();
8116         let node_count = routing_node_count + 2;
8117
8118         let chanmon_cfgs = create_chanmon_cfgs(node_count);
8119         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8120         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8121         let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8122
8123         let src_idx = 0;
8124         let dst_idx = 1;
8125
8126         // Create channels for each amount
8127         let mut expected_paths = Vec::with_capacity(routing_node_count);
8128         let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8129         let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8130         for i in 0..routing_node_count {
8131                 let routing_node = 2 + i;
8132                 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8133                 src_chan_ids.push(src_chan_id);
8134                 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8135                 dst_chan_ids.push(dst_chan_id);
8136                 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8137                 expected_paths.push(path);
8138         }
8139         let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8140
8141         // Create a route for each amount
8142         let example_amount = 100000;
8143         let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[src_idx], nodes[dst_idx], example_amount);
8144         let sample_path = route.paths.pop().unwrap();
8145         for i in 0..routing_node_count {
8146                 let routing_node = 2 + i;
8147                 let mut path = sample_path.clone();
8148                 path[0].pubkey = nodes[routing_node].node.get_our_node_id();
8149                 path[0].short_channel_id = src_chan_ids[i];
8150                 path[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8151                 path[1].short_channel_id = dst_chan_ids[i];
8152                 path[1].fee_msat = msat_amounts[i];
8153                 route.paths.push(path);
8154         }
8155
8156         // Send payment with manually set total_msat
8157         let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8158         let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8159                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8160         nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8161                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8162         check_added_monitors!(nodes[src_idx], expected_paths.len());
8163
8164         let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8165         assert_eq!(events.len(), expected_paths.len());
8166         let mut amount_received = 0;
8167         for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8168                 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8169
8170                 let current_path_amount = msat_amounts[path_idx];
8171                 amount_received += current_path_amount;
8172                 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8173                 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8174         }
8175
8176         claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8177 }
8178
8179 #[test]
8180 fn test_overshoot_mpp() {
8181         do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8182         do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8183 }
8184
8185 #[test]
8186 fn test_simple_mpp() {
8187         // Simple test of sending a multi-path payment.
8188         let chanmon_cfgs = create_chanmon_cfgs(4);
8189         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8190         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8191         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8192
8193         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8194         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8195         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8196         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8197
8198         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8199         let path = route.paths[0].clone();
8200         route.paths.push(path);
8201         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8202         route.paths[0][0].short_channel_id = chan_1_id;
8203         route.paths[0][1].short_channel_id = chan_3_id;
8204         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8205         route.paths[1][0].short_channel_id = chan_2_id;
8206         route.paths[1][1].short_channel_id = chan_4_id;
8207         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8208         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8209 }
8210
8211 #[test]
8212 fn test_preimage_storage() {
8213         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8214         let chanmon_cfgs = create_chanmon_cfgs(2);
8215         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8216         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8217         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8218
8219         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8220
8221         {
8222                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8223                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8224                 nodes[0].node.send_payment_with_route(&route, payment_hash,
8225                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8226                 check_added_monitors!(nodes[0], 1);
8227                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8228                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8229                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8230                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8231         }
8232         // Note that after leaving the above scope we have no knowledge of any arguments or return
8233         // values from previous calls.
8234         expect_pending_htlcs_forwardable!(nodes[1]);
8235         let events = nodes[1].node.get_and_clear_pending_events();
8236         assert_eq!(events.len(), 1);
8237         match events[0] {
8238                 Event::PaymentClaimable { ref purpose, .. } => {
8239                         match &purpose {
8240                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8241                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8242                                 },
8243                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8244                         }
8245                 },
8246                 _ => panic!("Unexpected event"),
8247         }
8248 }
8249
8250 #[test]
8251 #[allow(deprecated)]
8252 fn test_secret_timeout() {
8253         // Simple test of payment secret storage time outs. After
8254         // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8255         let chanmon_cfgs = create_chanmon_cfgs(2);
8256         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8257         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8258         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8259
8260         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8261
8262         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8263
8264         // We should fail to register the same payment hash twice, at least until we've connected a
8265         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8266         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8267                 assert_eq!(err, "Duplicate payment hash");
8268         } else { panic!(); }
8269         let mut block = {
8270                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8271                 Block {
8272                         header: BlockHeader {
8273                                 version: 0x2000000,
8274                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8275                                 merkle_root: TxMerkleNode::all_zeros(),
8276                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8277                         txdata: vec![],
8278                 }
8279         };
8280         connect_block(&nodes[1], &block);
8281         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8282                 assert_eq!(err, "Duplicate payment hash");
8283         } else { panic!(); }
8284
8285         // If we then connect the second block, we should be able to register the same payment hash
8286         // again (this time getting a new payment secret).
8287         block.header.prev_blockhash = block.header.block_hash();
8288         block.header.time += 1;
8289         connect_block(&nodes[1], &block);
8290         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8291         assert_ne!(payment_secret_1, our_payment_secret);
8292
8293         {
8294                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8295                 nodes[0].node.send_payment_with_route(&route, payment_hash,
8296                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(payment_hash.0)).unwrap();
8297                 check_added_monitors!(nodes[0], 1);
8298                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8299                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8300                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8301                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8302         }
8303         // Note that after leaving the above scope we have no knowledge of any arguments or return
8304         // values from previous calls.
8305         expect_pending_htlcs_forwardable!(nodes[1]);
8306         let events = nodes[1].node.get_and_clear_pending_events();
8307         assert_eq!(events.len(), 1);
8308         match events[0] {
8309                 Event::PaymentClaimable { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8310                         assert!(payment_preimage.is_none());
8311                         assert_eq!(payment_secret, our_payment_secret);
8312                         // We don't actually have the payment preimage with which to claim this payment!
8313                 },
8314                 _ => panic!("Unexpected event"),
8315         }
8316 }
8317
8318 #[test]
8319 fn test_bad_secret_hash() {
8320         // Simple test of unregistered payment hash/invalid payment secret handling
8321         let chanmon_cfgs = create_chanmon_cfgs(2);
8322         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8323         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8324         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8325
8326         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8327
8328         let random_payment_hash = PaymentHash([42; 32]);
8329         let random_payment_secret = PaymentSecret([43; 32]);
8330         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8331         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8332
8333         // All the below cases should end up being handled exactly identically, so we macro the
8334         // resulting events.
8335         macro_rules! handle_unknown_invalid_payment_data {
8336                 ($payment_hash: expr) => {
8337                         check_added_monitors!(nodes[0], 1);
8338                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8339                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8340                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8341                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8342
8343                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8344                         // again to process the pending backwards-failure of the HTLC
8345                         expect_pending_htlcs_forwardable!(nodes[1]);
8346                         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8347                         check_added_monitors!(nodes[1], 1);
8348
8349                         // We should fail the payment back
8350                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8351                         match events.pop().unwrap() {
8352                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8353                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8354                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8355                                 },
8356                                 _ => panic!("Unexpected event"),
8357                         }
8358                 }
8359         }
8360
8361         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8362         // Error data is the HTLC value (100,000) and current block height
8363         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8364
8365         // Send a payment with the right payment hash but the wrong payment secret
8366         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8367                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8368         handle_unknown_invalid_payment_data!(our_payment_hash);
8369         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8370
8371         // Send a payment with a random payment hash, but the right payment secret
8372         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8373                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8374         handle_unknown_invalid_payment_data!(random_payment_hash);
8375         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8376
8377         // Send a payment with a random payment hash and random payment secret
8378         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8379                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8380         handle_unknown_invalid_payment_data!(random_payment_hash);
8381         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8382 }
8383
8384 #[test]
8385 fn test_update_err_monitor_lockdown() {
8386         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8387         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8388         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8389         // error.
8390         //
8391         // This scenario may happen in a watchtower setup, where watchtower process a block height
8392         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8393         // commitment at same time.
8394
8395         let chanmon_cfgs = create_chanmon_cfgs(2);
8396         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8397         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8398         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8399
8400         // Create some initial channel
8401         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8402         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8403
8404         // Rebalance the network to generate htlc in the two directions
8405         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8406
8407         // Route a HTLC from node 0 to node 1 (but don't settle)
8408         let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8409
8410         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8411         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8412         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8413         let persister = test_utils::TestPersister::new();
8414         let watchtower = {
8415                 let new_monitor = {
8416                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8417                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8418                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8419                         assert!(new_monitor == *monitor);
8420                         new_monitor
8421                 };
8422                 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);
8423                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8424                 watchtower
8425         };
8426         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8427         let block = Block { header, txdata: vec![] };
8428         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8429         // transaction lock time requirements here.
8430         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8431         watchtower.chain_monitor.block_connected(&block, 200);
8432
8433         // Try to update ChannelMonitor
8434         nodes[1].node.claim_funds(preimage);
8435         check_added_monitors!(nodes[1], 1);
8436         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8437
8438         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8439         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8440         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8441         {
8442                 let mut node_0_per_peer_lock;
8443                 let mut node_0_peer_state_lock;
8444                 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8445                 if let Ok(update) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8446                         assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8447                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8448                 } else { assert!(false); }
8449         }
8450         // Our local monitor is in-sync and hasn't processed yet timeout
8451         check_added_monitors!(nodes[0], 1);
8452         let events = nodes[0].node.get_and_clear_pending_events();
8453         assert_eq!(events.len(), 1);
8454 }
8455
8456 #[test]
8457 fn test_concurrent_monitor_claim() {
8458         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8459         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8460         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8461         // state N+1 confirms. Alice claims output from state N+1.
8462
8463         let chanmon_cfgs = create_chanmon_cfgs(2);
8464         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8465         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8466         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8467
8468         // Create some initial channel
8469         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8470         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8471
8472         // Rebalance the network to generate htlc in the two directions
8473         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8474
8475         // Route a HTLC from node 0 to node 1 (but don't settle)
8476         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8477
8478         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8479         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8480         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8481         let persister = test_utils::TestPersister::new();
8482         let watchtower_alice = {
8483                 let new_monitor = {
8484                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8485                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8486                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8487                         assert!(new_monitor == *monitor);
8488                         new_monitor
8489                 };
8490                 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);
8491                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8492                 watchtower
8493         };
8494         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8495         let block = Block { header, txdata: vec![] };
8496         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8497         // transaction lock time requirements here.
8498         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));
8499         watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8500
8501         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8502         {
8503                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8504                 assert_eq!(txn.len(), 2);
8505                 txn.clear();
8506         }
8507
8508         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8509         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8510         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8511         let persister = test_utils::TestPersister::new();
8512         let watchtower_bob = {
8513                 let new_monitor = {
8514                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8515                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8516                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8517                         assert!(new_monitor == *monitor);
8518                         new_monitor
8519                 };
8520                 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);
8521                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8522                 watchtower
8523         };
8524         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8525         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8526
8527         // Route another payment to generate another update with still previous HTLC pending
8528         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8529         nodes[1].node.send_payment_with_route(&route, payment_hash,
8530                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8531         check_added_monitors!(nodes[1], 1);
8532
8533         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8534         assert_eq!(updates.update_add_htlcs.len(), 1);
8535         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8536         {
8537                 let mut node_0_per_peer_lock;
8538                 let mut node_0_peer_state_lock;
8539                 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8540                 if let Ok(update) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8541                         // Watchtower Alice should already have seen the block and reject the update
8542                         assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8543                         assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8544                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8545                 } else { assert!(false); }
8546         }
8547         // Our local monitor is in-sync and hasn't processed yet timeout
8548         check_added_monitors!(nodes[0], 1);
8549
8550         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8551         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8552         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8553
8554         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8555         let bob_state_y;
8556         {
8557                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8558                 assert_eq!(txn.len(), 2);
8559                 bob_state_y = txn[0].clone();
8560                 txn.clear();
8561         };
8562
8563         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8564         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8565         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);
8566         {
8567                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8568                 assert_eq!(htlc_txn.len(), 1);
8569                 check_spends!(htlc_txn[0], bob_state_y);
8570         }
8571 }
8572
8573 #[test]
8574 fn test_pre_lockin_no_chan_closed_update() {
8575         // Test that if a peer closes a channel in response to a funding_created message we don't
8576         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8577         // message).
8578         //
8579         // Doing so would imply a channel monitor update before the initial channel monitor
8580         // registration, violating our API guarantees.
8581         //
8582         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8583         // then opening a second channel with the same funding output as the first (which is not
8584         // rejected because the first channel does not exist in the ChannelManager) and closing it
8585         // before receiving funding_signed.
8586         let chanmon_cfgs = create_chanmon_cfgs(2);
8587         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8588         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8589         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8590
8591         // Create an initial channel
8592         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8593         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8594         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8595         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8596         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8597
8598         // Move the first channel through the funding flow...
8599         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8600
8601         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8602         check_added_monitors!(nodes[0], 0);
8603
8604         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8605         let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8606         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8607         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8608         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true);
8609 }
8610
8611 #[test]
8612 fn test_htlc_no_detection() {
8613         // This test is a mutation to underscore the detection logic bug we had
8614         // before #653. HTLC value routed is above the remaining balance, thus
8615         // inverting HTLC and `to_remote` output. HTLC will come second and
8616         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8617         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8618         // outputs order detection for correct spending children filtring.
8619
8620         let chanmon_cfgs = create_chanmon_cfgs(2);
8621         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8622         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8623         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8624
8625         // Create some initial channels
8626         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8627
8628         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8629         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8630         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8631         assert_eq!(local_txn[0].input.len(), 1);
8632         assert_eq!(local_txn[0].output.len(), 3);
8633         check_spends!(local_txn[0], chan_1.3);
8634
8635         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8636         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8637         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8638         // We deliberately connect the local tx twice as this should provoke a failure calling
8639         // this test before #653 fix.
8640         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);
8641         check_closed_broadcast!(nodes[0], true);
8642         check_added_monitors!(nodes[0], 1);
8643         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8644         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8645
8646         let htlc_timeout = {
8647                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8648                 assert_eq!(node_txn.len(), 1);
8649                 assert_eq!(node_txn[0].input.len(), 1);
8650                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8651                 check_spends!(node_txn[0], local_txn[0]);
8652                 node_txn[0].clone()
8653         };
8654
8655         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8656         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8657         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8658         expect_payment_failed!(nodes[0], our_payment_hash, false);
8659 }
8660
8661 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8662         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8663         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8664         // Carol, Alice would be the upstream node, and Carol the downstream.)
8665         //
8666         // Steps of the test:
8667         // 1) Alice sends a HTLC to Carol through Bob.
8668         // 2) Carol doesn't settle the HTLC.
8669         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8670         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8671         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8672         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8673         // 5) Carol release the preimage to Bob off-chain.
8674         // 6) Bob claims the offered output on the broadcasted commitment.
8675         let chanmon_cfgs = create_chanmon_cfgs(3);
8676         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8677         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8678         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8679
8680         // Create some initial channels
8681         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8682         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8683
8684         // Steps (1) and (2):
8685         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8686         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8687
8688         // Check that Alice's commitment transaction now contains an output for this HTLC.
8689         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8690         check_spends!(alice_txn[0], chan_ab.3);
8691         assert_eq!(alice_txn[0].output.len(), 2);
8692         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8693         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8694         assert_eq!(alice_txn.len(), 2);
8695
8696         // Steps (3) and (4):
8697         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8698         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8699         let mut force_closing_node = 0; // Alice force-closes
8700         let mut counterparty_node = 1; // Bob if Alice force-closes
8701
8702         // Bob force-closes
8703         if !broadcast_alice {
8704                 force_closing_node = 1;
8705                 counterparty_node = 0;
8706         }
8707         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8708         check_closed_broadcast!(nodes[force_closing_node], true);
8709         check_added_monitors!(nodes[force_closing_node], 1);
8710         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8711         if go_onchain_before_fulfill {
8712                 let txn_to_broadcast = match broadcast_alice {
8713                         true => alice_txn.clone(),
8714                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8715                 };
8716                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8717                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8718                 if broadcast_alice {
8719                         check_closed_broadcast!(nodes[1], true);
8720                         check_added_monitors!(nodes[1], 1);
8721                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8722                 }
8723         }
8724
8725         // Step (5):
8726         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8727         // process of removing the HTLC from their commitment transactions.
8728         nodes[2].node.claim_funds(payment_preimage);
8729         check_added_monitors!(nodes[2], 1);
8730         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8731
8732         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8733         assert!(carol_updates.update_add_htlcs.is_empty());
8734         assert!(carol_updates.update_fail_htlcs.is_empty());
8735         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8736         assert!(carol_updates.update_fee.is_none());
8737         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8738
8739         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8740         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8741         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8742         if !go_onchain_before_fulfill && broadcast_alice {
8743                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8744                 assert_eq!(events.len(), 1);
8745                 match events[0] {
8746                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8747                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8748                         },
8749                         _ => panic!("Unexpected event"),
8750                 };
8751         }
8752         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8753         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8754         // Carol<->Bob's updated commitment transaction info.
8755         check_added_monitors!(nodes[1], 2);
8756
8757         let events = nodes[1].node.get_and_clear_pending_msg_events();
8758         assert_eq!(events.len(), 2);
8759         let bob_revocation = match events[0] {
8760                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8761                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8762                         (*msg).clone()
8763                 },
8764                 _ => panic!("Unexpected event"),
8765         };
8766         let bob_updates = match events[1] {
8767                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8768                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8769                         (*updates).clone()
8770                 },
8771                 _ => panic!("Unexpected event"),
8772         };
8773
8774         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8775         check_added_monitors!(nodes[2], 1);
8776         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8777         check_added_monitors!(nodes[2], 1);
8778
8779         let events = nodes[2].node.get_and_clear_pending_msg_events();
8780         assert_eq!(events.len(), 1);
8781         let carol_revocation = match events[0] {
8782                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8783                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8784                         (*msg).clone()
8785                 },
8786                 _ => panic!("Unexpected event"),
8787         };
8788         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8789         check_added_monitors!(nodes[1], 1);
8790
8791         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8792         // here's where we put said channel's commitment tx on-chain.
8793         let mut txn_to_broadcast = alice_txn.clone();
8794         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8795         if !go_onchain_before_fulfill {
8796                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8797                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8798                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8799                 if broadcast_alice {
8800                         check_closed_broadcast!(nodes[1], true);
8801                         check_added_monitors!(nodes[1], 1);
8802                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8803                 }
8804                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8805                 if broadcast_alice {
8806                         assert_eq!(bob_txn.len(), 1);
8807                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8808                 } else {
8809                         assert_eq!(bob_txn.len(), 2);
8810                         check_spends!(bob_txn[0], chan_ab.3);
8811                 }
8812         }
8813
8814         // Step (6):
8815         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8816         // broadcasted commitment transaction.
8817         {
8818                 let script_weight = match broadcast_alice {
8819                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8820                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8821                 };
8822                 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8823                 // Bob force-closed and broadcasts the commitment transaction along with a
8824                 // HTLC-output-claiming transaction.
8825                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8826                 if broadcast_alice {
8827                         assert_eq!(bob_txn.len(), 1);
8828                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8829                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8830                 } else {
8831                         assert_eq!(bob_txn.len(), 2);
8832                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8833                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8834                 }
8835         }
8836 }
8837
8838 #[test]
8839 fn test_onchain_htlc_settlement_after_close() {
8840         do_test_onchain_htlc_settlement_after_close(true, true);
8841         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8842         do_test_onchain_htlc_settlement_after_close(true, false);
8843         do_test_onchain_htlc_settlement_after_close(false, false);
8844 }
8845
8846 #[test]
8847 fn test_duplicate_temporary_channel_id_from_different_peers() {
8848         // Tests that we can accept two different `OpenChannel` requests with the same
8849         // `temporary_channel_id`, as long as they are from different peers.
8850         let chanmon_cfgs = create_chanmon_cfgs(3);
8851         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8852         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8853         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8854
8855         // Create an first channel channel
8856         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8857         let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8858
8859         // Create an second channel
8860         nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8861         let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8862
8863         // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8864         // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8865         open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8866
8867         // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8868         // `temporary_channel_id` as they are from different peers.
8869         nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8870         {
8871                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8872                 assert_eq!(events.len(), 1);
8873                 match &events[0] {
8874                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8875                                 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8876                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8877                         },
8878                         _ => panic!("Unexpected event"),
8879                 }
8880         }
8881
8882         nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8883         {
8884                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8885                 assert_eq!(events.len(), 1);
8886                 match &events[0] {
8887                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8888                                 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8889                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8890                         },
8891                         _ => panic!("Unexpected event"),
8892                 }
8893         }
8894 }
8895
8896 #[test]
8897 fn test_duplicate_chan_id() {
8898         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8899         // already open we reject it and keep the old channel.
8900         //
8901         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8902         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8903         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8904         // updating logic for the existing channel.
8905         let chanmon_cfgs = create_chanmon_cfgs(2);
8906         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8907         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8908         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8909
8910         // Create an initial channel
8911         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8912         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8913         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8914         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()));
8915
8916         // Try to create a second channel with the same temporary_channel_id as the first and check
8917         // that it is rejected.
8918         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8919         {
8920                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8921                 assert_eq!(events.len(), 1);
8922                 match events[0] {
8923                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8924                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8925                                 // first (valid) and second (invalid) channels are closed, given they both have
8926                                 // the same non-temporary channel_id. However, currently we do not, so we just
8927                                 // move forward with it.
8928                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8929                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8930                         },
8931                         _ => panic!("Unexpected event"),
8932                 }
8933         }
8934
8935         // Move the first channel through the funding flow...
8936         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8937
8938         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8939         check_added_monitors!(nodes[0], 0);
8940
8941         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8942         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8943         {
8944                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8945                 assert_eq!(added_monitors.len(), 1);
8946                 assert_eq!(added_monitors[0].0, funding_output);
8947                 added_monitors.clear();
8948         }
8949         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
8950
8951         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8952
8953         let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8954         let channel_id = funding_outpoint.to_channel_id();
8955
8956         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8957         // temporary one).
8958
8959         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8960         // Technically this is allowed by the spec, but we don't support it and there's little reason
8961         // to. Still, it shouldn't cause any other issues.
8962         open_chan_msg.temporary_channel_id = channel_id;
8963         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8964         {
8965                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8966                 assert_eq!(events.len(), 1);
8967                 match events[0] {
8968                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8969                                 // Technically, at this point, nodes[1] would be justified in thinking both
8970                                 // channels are closed, but currently we do not, so we just move forward with it.
8971                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8972                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8973                         },
8974                         _ => panic!("Unexpected event"),
8975                 }
8976         }
8977
8978         // Now try to create a second channel which has a duplicate funding output.
8979         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8980         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8981         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
8982         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()));
8983         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8984
8985         let funding_created = {
8986                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8987                 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
8988                 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
8989                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8990                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8991                 // channelmanager in a possibly nonsense state instead).
8992                 let mut as_chan = a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8993                 let logger = test_utils::TestLogger::new();
8994                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8995         };
8996         check_added_monitors!(nodes[0], 0);
8997         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8998         // At this point we'll look up if the channel_id is present and immediately fail the channel
8999         // without trying to persist the `ChannelMonitor`.
9000         check_added_monitors!(nodes[1], 0);
9001
9002         // ...still, nodes[1] will reject the duplicate channel.
9003         {
9004                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9005                 assert_eq!(events.len(), 1);
9006                 match events[0] {
9007                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9008                                 // Technically, at this point, nodes[1] would be justified in thinking both
9009                                 // channels are closed, but currently we do not, so we just move forward with it.
9010                                 assert_eq!(msg.channel_id, channel_id);
9011                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9012                         },
9013                         _ => panic!("Unexpected event"),
9014                 }
9015         }
9016
9017         // finally, finish creating the original channel and send a payment over it to make sure
9018         // everything is functional.
9019         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9020         {
9021                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9022                 assert_eq!(added_monitors.len(), 1);
9023                 assert_eq!(added_monitors[0].0, funding_output);
9024                 added_monitors.clear();
9025         }
9026         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9027
9028         let events_4 = nodes[0].node.get_and_clear_pending_events();
9029         assert_eq!(events_4.len(), 0);
9030         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9031         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9032
9033         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9034         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9035         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9036
9037         send_payment(&nodes[0], &[&nodes[1]], 8000000);
9038 }
9039
9040 #[test]
9041 fn test_error_chans_closed() {
9042         // Test that we properly handle error messages, closing appropriate channels.
9043         //
9044         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9045         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9046         // we can test various edge cases around it to ensure we don't regress.
9047         let chanmon_cfgs = create_chanmon_cfgs(3);
9048         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9049         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9050         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9051
9052         // Create some initial channels
9053         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9054         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9055         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
9056
9057         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9058         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9059         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9060
9061         // Closing a channel from a different peer has no effect
9062         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9063         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9064
9065         // Closing one channel doesn't impact others
9066         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9067         check_added_monitors!(nodes[0], 1);
9068         check_closed_broadcast!(nodes[0], false);
9069         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
9070         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9071         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9072         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);
9073         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);
9074
9075         // A null channel ID should close all channels
9076         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9077         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9078         check_added_monitors!(nodes[0], 2);
9079         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
9080         let events = nodes[0].node.get_and_clear_pending_msg_events();
9081         assert_eq!(events.len(), 2);
9082         match events[0] {
9083                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9084                         assert_eq!(msg.contents.flags & 2, 2);
9085                 },
9086                 _ => panic!("Unexpected event"),
9087         }
9088         match events[1] {
9089                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9090                         assert_eq!(msg.contents.flags & 2, 2);
9091                 },
9092                 _ => panic!("Unexpected event"),
9093         }
9094         // Note that at this point users of a standard PeerHandler will end up calling
9095         // peer_disconnected.
9096         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9097         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9098
9099         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9100         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9101         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9102 }
9103
9104 #[test]
9105 fn test_invalid_funding_tx() {
9106         // Test that we properly handle invalid funding transactions sent to us from a peer.
9107         //
9108         // Previously, all other major lightning implementations had failed to properly sanitize
9109         // funding transactions from their counterparties, leading to a multi-implementation critical
9110         // security vulnerability (though we always sanitized properly, we've previously had
9111         // un-released crashes in the sanitization process).
9112         //
9113         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9114         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9115         // gave up on it. We test this here by generating such a transaction.
9116         let chanmon_cfgs = create_chanmon_cfgs(2);
9117         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9118         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9119         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9120
9121         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9122         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()));
9123         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()));
9124
9125         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9126
9127         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9128         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9129         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9130         // its length.
9131         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9132         let wit_program_script: Script = wit_program.into();
9133         for output in tx.output.iter_mut() {
9134                 // Make the confirmed funding transaction have a bogus script_pubkey
9135                 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9136         }
9137
9138         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9139         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()));
9140         check_added_monitors!(nodes[1], 1);
9141         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9142
9143         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()));
9144         check_added_monitors!(nodes[0], 1);
9145         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9146
9147         let events_1 = nodes[0].node.get_and_clear_pending_events();
9148         assert_eq!(events_1.len(), 0);
9149
9150         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9151         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9152         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9153
9154         let expected_err = "funding tx had wrong script/value or output index";
9155         confirm_transaction_at(&nodes[1], &tx, 1);
9156         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9157         check_added_monitors!(nodes[1], 1);
9158         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9159         assert_eq!(events_2.len(), 1);
9160         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9161                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9162                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9163                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9164                 } else { panic!(); }
9165         } else { panic!(); }
9166         assert_eq!(nodes[1].node.list_channels().len(), 0);
9167
9168         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9169         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9170         // as its not 32 bytes long.
9171         let mut spend_tx = Transaction {
9172                 version: 2i32, lock_time: PackedLockTime::ZERO,
9173                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9174                         previous_output: BitcoinOutPoint {
9175                                 txid: tx.txid(),
9176                                 vout: idx as u32,
9177                         },
9178                         script_sig: Script::new(),
9179                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9180                         witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9181                 }).collect(),
9182                 output: vec![TxOut {
9183                         value: 1000,
9184                         script_pubkey: Script::new(),
9185                 }]
9186         };
9187         check_spends!(spend_tx, tx);
9188         mine_transaction(&nodes[1], &spend_tx);
9189 }
9190
9191 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9192         // In the first version of the chain::Confirm interface, after a refactor was made to not
9193         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9194         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9195         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9196         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9197         // spending transaction until height N+1 (or greater). This was due to the way
9198         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9199         // spending transaction at the height the input transaction was confirmed at, not whether we
9200         // should broadcast a spending transaction at the current height.
9201         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9202         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9203         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9204         // until we learned about an additional block.
9205         //
9206         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9207         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9208         let chanmon_cfgs = create_chanmon_cfgs(3);
9209         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9210         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9211         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9212         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9213
9214         create_announced_chan_between_nodes(&nodes, 0, 1);
9215         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9216         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9217         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9218         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9219
9220         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9221         check_closed_broadcast!(nodes[1], true);
9222         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9223         check_added_monitors!(nodes[1], 1);
9224         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9225         assert_eq!(node_txn.len(), 1);
9226
9227         let conf_height = nodes[1].best_block_info().1;
9228         if !test_height_before_timelock {
9229                 connect_blocks(&nodes[1], 24 * 6);
9230         }
9231         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9232                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9233         if test_height_before_timelock {
9234                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9235                 // generate any events or broadcast any transactions
9236                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9237                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9238         } else {
9239                 // We should broadcast an HTLC transaction spending our funding transaction first
9240                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9241                 assert_eq!(spending_txn.len(), 2);
9242                 assert_eq!(spending_txn[0], node_txn[0]);
9243                 check_spends!(spending_txn[1], node_txn[0]);
9244                 // We should also generate a SpendableOutputs event with the to_self output (as its
9245                 // timelock is up).
9246                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9247                 assert_eq!(descriptor_spend_txn.len(), 1);
9248
9249                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9250                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9251                 // additional block built on top of the current chain.
9252                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9253                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9254                 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 }]);
9255                 check_added_monitors!(nodes[1], 1);
9256
9257                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9258                 assert!(updates.update_add_htlcs.is_empty());
9259                 assert!(updates.update_fulfill_htlcs.is_empty());
9260                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9261                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9262                 assert!(updates.update_fee.is_none());
9263                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9264                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9265                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9266         }
9267 }
9268
9269 #[test]
9270 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9271         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9272         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9273 }
9274
9275 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9276         let chanmon_cfgs = create_chanmon_cfgs(2);
9277         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9278         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9279         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9280
9281         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9282
9283         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9284                 .with_features(nodes[1].node.invoice_features());
9285         let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9286
9287         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9288
9289         {
9290                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9291                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9292                 check_added_monitors!(nodes[0], 1);
9293                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9294                 assert_eq!(events.len(), 1);
9295                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9296                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9297                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9298         }
9299         expect_pending_htlcs_forwardable!(nodes[1]);
9300         expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9301
9302         {
9303                 // Note that we use a different PaymentId here to allow us to duplicativly pay
9304                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9305                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9306                 check_added_monitors!(nodes[0], 1);
9307                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9308                 assert_eq!(events.len(), 1);
9309                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9310                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9311                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9312                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9313                 // assume the second is a privacy attack (no longer particularly relevant
9314                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9315                 // the first HTLC delivered above.
9316         }
9317
9318         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9319         nodes[1].node.process_pending_htlc_forwards();
9320
9321         if test_for_second_fail_panic {
9322                 // Now we go fail back the first HTLC from the user end.
9323                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9324
9325                 let expected_destinations = vec![
9326                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9327                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9328                 ];
9329                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],  expected_destinations);
9330                 nodes[1].node.process_pending_htlc_forwards();
9331
9332                 check_added_monitors!(nodes[1], 1);
9333                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9334                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9335
9336                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9337                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9338                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9339
9340                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9341                 assert_eq!(failure_events.len(), 4);
9342                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9343                 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9344                 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9345                 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9346         } else {
9347                 // Let the second HTLC fail and claim the first
9348                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9349                 nodes[1].node.process_pending_htlc_forwards();
9350
9351                 check_added_monitors!(nodes[1], 1);
9352                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9353                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9354                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9355
9356                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9357
9358                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9359         }
9360 }
9361
9362 #[test]
9363 fn test_dup_htlc_second_fail_panic() {
9364         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9365         // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9366         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9367         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9368         do_test_dup_htlc_second_rejected(true);
9369 }
9370
9371 #[test]
9372 fn test_dup_htlc_second_rejected() {
9373         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9374         // simply reject the second HTLC but are still able to claim the first HTLC.
9375         do_test_dup_htlc_second_rejected(false);
9376 }
9377
9378 #[test]
9379 fn test_inconsistent_mpp_params() {
9380         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9381         // such HTLC and allow the second to stay.
9382         let chanmon_cfgs = create_chanmon_cfgs(4);
9383         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9384         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9385         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9386
9387         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9388         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9389         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9390         let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9391
9392         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9393                 .with_features(nodes[3].node.invoice_features());
9394         let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9395         assert_eq!(route.paths.len(), 2);
9396         route.paths.sort_by(|path_a, _| {
9397                 // Sort the path so that the path through nodes[1] comes first
9398                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9399                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9400         });
9401
9402         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9403
9404         let cur_height = nodes[0].best_block_info().1;
9405         let payment_id = PaymentId([42; 32]);
9406
9407         let session_privs = {
9408                 // We create a fake route here so that we start with three pending HTLCs, which we'll
9409                 // ultimately have, just not right away.
9410                 let mut dup_route = route.clone();
9411                 dup_route.paths.push(route.paths[1].clone());
9412                 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9413                         RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9414         };
9415         nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9416                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9417                 &None, session_privs[0]).unwrap();
9418         check_added_monitors!(nodes[0], 1);
9419
9420         {
9421                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9422                 assert_eq!(events.len(), 1);
9423                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9424         }
9425         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9426
9427         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9428                 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9429         check_added_monitors!(nodes[0], 1);
9430
9431         {
9432                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9433                 assert_eq!(events.len(), 1);
9434                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9435
9436                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9437                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9438
9439                 expect_pending_htlcs_forwardable!(nodes[2]);
9440                 check_added_monitors!(nodes[2], 1);
9441
9442                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9443                 assert_eq!(events.len(), 1);
9444                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9445
9446                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9447                 check_added_monitors!(nodes[3], 0);
9448                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9449
9450                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9451                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9452                 // post-payment_secrets) and fail back the new HTLC.
9453         }
9454         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9455         nodes[3].node.process_pending_htlc_forwards();
9456         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9457         nodes[3].node.process_pending_htlc_forwards();
9458
9459         check_added_monitors!(nodes[3], 1);
9460
9461         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9462         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9463         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9464
9465         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 }]);
9466         check_added_monitors!(nodes[2], 1);
9467
9468         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9469         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9470         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9471
9472         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9473
9474         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9475                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9476                 &None, session_privs[2]).unwrap();
9477         check_added_monitors!(nodes[0], 1);
9478
9479         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9480         assert_eq!(events.len(), 1);
9481         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9482
9483         do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9484         let events = nodes[0].node.get_and_clear_pending_events();
9485         assert_eq!(events.len(), 3);
9486         match events[0] {
9487                 Event::PaymentSent { payment_hash, .. } => { // The payment was abandoned earlier, so the fee paid will be None
9488                         assert_eq!(payment_hash, our_payment_hash);
9489                 },
9490                 _ => panic!("Unexpected event")
9491         }
9492         match events[1] {
9493                 Event::PaymentPathSuccessful { payment_hash, .. } => {
9494                         assert_eq!(payment_hash.unwrap(), our_payment_hash);
9495                 },
9496                 _ => panic!("Unexpected event")
9497         }
9498         match events[2] {
9499                 Event::PaymentPathSuccessful { payment_hash, .. } => {
9500                         assert_eq!(payment_hash.unwrap(), our_payment_hash);
9501                 },
9502                 _ => panic!("Unexpected event")
9503         }
9504 }
9505
9506 #[test]
9507 fn test_keysend_payments_to_public_node() {
9508         let chanmon_cfgs = create_chanmon_cfgs(2);
9509         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9510         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9511         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9512
9513         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9514         let network_graph = nodes[0].network_graph.clone();
9515         let payer_pubkey = nodes[0].node.get_our_node_id();
9516         let payee_pubkey = nodes[1].node.get_our_node_id();
9517         let route_params = RouteParameters {
9518                 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9519                 final_value_msat: 10000,
9520         };
9521         let scorer = test_utils::TestScorer::new();
9522         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9523         let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9524
9525         let test_preimage = PaymentPreimage([42; 32]);
9526         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
9527                 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
9528         check_added_monitors!(nodes[0], 1);
9529         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9530         assert_eq!(events.len(), 1);
9531         let event = events.pop().unwrap();
9532         let path = vec![&nodes[1]];
9533         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9534         claim_payment(&nodes[0], &path, test_preimage);
9535 }
9536
9537 #[test]
9538 fn test_keysend_payments_to_private_node() {
9539         let chanmon_cfgs = create_chanmon_cfgs(2);
9540         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9541         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9542         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9543
9544         let payer_pubkey = nodes[0].node.get_our_node_id();
9545         let payee_pubkey = nodes[1].node.get_our_node_id();
9546
9547         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
9548         let route_params = RouteParameters {
9549                 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9550                 final_value_msat: 10000,
9551         };
9552         let network_graph = nodes[0].network_graph.clone();
9553         let first_hops = nodes[0].node.list_usable_channels();
9554         let scorer = test_utils::TestScorer::new();
9555         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9556         let route = find_route(
9557                 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9558                 nodes[0].logger, &scorer, &random_seed_bytes
9559         ).unwrap();
9560
9561         let test_preimage = PaymentPreimage([42; 32]);
9562         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
9563                 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
9564         check_added_monitors!(nodes[0], 1);
9565         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9566         assert_eq!(events.len(), 1);
9567         let event = events.pop().unwrap();
9568         let path = vec![&nodes[1]];
9569         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9570         claim_payment(&nodes[0], &path, test_preimage);
9571 }
9572
9573 #[test]
9574 fn test_double_partial_claim() {
9575         // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9576         // time out, the sender resends only some of the MPP parts, then the user processes the
9577         // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9578         // amount.
9579         let chanmon_cfgs = create_chanmon_cfgs(4);
9580         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9581         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9582         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9583
9584         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9585         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9586         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9587         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9588
9589         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9590         assert_eq!(route.paths.len(), 2);
9591         route.paths.sort_by(|path_a, _| {
9592                 // Sort the path so that the path through nodes[1] comes first
9593                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9594                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9595         });
9596
9597         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9598         // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9599         // amount of time to respond to.
9600
9601         // Connect some blocks to time out the payment
9602         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9603         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9604
9605         let failed_destinations = vec![
9606                 HTLCDestination::FailedPayment { payment_hash },
9607                 HTLCDestination::FailedPayment { payment_hash },
9608         ];
9609         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9610
9611         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9612
9613         // nodes[1] now retries one of the two paths...
9614         nodes[0].node.send_payment_with_route(&route, payment_hash,
9615                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9616         check_added_monitors!(nodes[0], 2);
9617
9618         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9619         assert_eq!(events.len(), 2);
9620         let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9621         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9622
9623         // At this point nodes[3] has received one half of the payment, and the user goes to handle
9624         // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9625         nodes[3].node.claim_funds(payment_preimage);
9626         check_added_monitors!(nodes[3], 0);
9627         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9628 }
9629
9630 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9631 #[derive(Clone, Copy, PartialEq)]
9632 enum ExposureEvent {
9633         /// Breach occurs at HTLC forwarding (see `send_htlc`)
9634         AtHTLCForward,
9635         /// Breach occurs at HTLC reception (see `update_add_htlc`)
9636         AtHTLCReception,
9637         /// Breach occurs at outbound update_fee (see `send_update_fee`)
9638         AtUpdateFeeOutbound,
9639 }
9640
9641 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9642         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9643         // policy.
9644         //
9645         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9646         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9647         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9648         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9649         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9650         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9651         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9652         // might be available again for HTLC processing once the dust bandwidth has cleared up.
9653
9654         let chanmon_cfgs = create_chanmon_cfgs(2);
9655         let mut config = test_default_channel_config();
9656         config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9657         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9658         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9659         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9660
9661         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9662         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9663         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9664         open_channel.max_accepted_htlcs = 60;
9665         if on_holder_tx {
9666                 open_channel.dust_limit_satoshis = 546;
9667         }
9668         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9669         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9670         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9671
9672         let opt_anchors = false;
9673
9674         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9675
9676         if on_holder_tx {
9677                 let mut node_0_per_peer_lock;
9678                 let mut node_0_peer_state_lock;
9679                 let mut chan = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id);
9680                 chan.holder_dust_limit_satoshis = 546;
9681         }
9682
9683         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9684         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()));
9685         check_added_monitors!(nodes[1], 1);
9686         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9687
9688         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()));
9689         check_added_monitors!(nodes[0], 1);
9690         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9691
9692         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9693         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9694         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9695
9696         let dust_buffer_feerate = {
9697                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9698                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9699                 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9700                 chan.get_dust_buffer_feerate(None) as u64
9701         };
9702         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;
9703         let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9704
9705         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;
9706         let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9707
9708         let dust_htlc_on_counterparty_tx: u64 = 25;
9709         let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9710
9711         if on_holder_tx {
9712                 if dust_outbound_balance {
9713                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9714                         // Outbound dust balance: 4372 sats
9715                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9716                         for _ in 0..dust_outbound_htlc_on_holder_tx {
9717                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9718                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9719                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9720                         }
9721                 } else {
9722                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9723                         // Inbound dust balance: 4372 sats
9724                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9725                         for _ in 0..dust_inbound_htlc_on_holder_tx {
9726                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9727                         }
9728                 }
9729         } else {
9730                 if dust_outbound_balance {
9731                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9732                         // Outbound dust balance: 5000 sats
9733                         for _ in 0..dust_htlc_on_counterparty_tx {
9734                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9735                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9736                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9737                         }
9738                 } else {
9739                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9740                         // Inbound dust balance: 5000 sats
9741                         for _ in 0..dust_htlc_on_counterparty_tx {
9742                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9743                         }
9744                 }
9745         }
9746
9747         let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9748         if exposure_breach_event == ExposureEvent::AtHTLCForward {
9749                 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 });
9750                 let mut config = UserConfig::default();
9751                 // With default dust exposure: 5000 sats
9752                 if on_holder_tx {
9753                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9754                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9755                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9756                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9757                                 ), true, APIError::ChannelUnavailable { ref err },
9758                                 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)));
9759                 } else {
9760                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9761                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9762                                 ), true, APIError::ChannelUnavailable { ref err },
9763                                 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)));
9764                 }
9765         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9766                 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 });
9767                 nodes[1].node.send_payment_with_route(&route, payment_hash,
9768                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9769                 check_added_monitors!(nodes[1], 1);
9770                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9771                 assert_eq!(events.len(), 1);
9772                 let payment_event = SendEvent::from_event(events.remove(0));
9773                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9774                 // With default dust exposure: 5000 sats
9775                 if on_holder_tx {
9776                         // Outbound dust balance: 6399 sats
9777                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9778                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9779                         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);
9780                 } else {
9781                         // Outbound dust balance: 5200 sats
9782                         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);
9783                 }
9784         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9785                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
9786                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9787                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9788                 {
9789                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9790                         *feerate_lock = *feerate_lock * 10;
9791                 }
9792                 nodes[0].node.timer_tick_occurred();
9793                 check_added_monitors!(nodes[0], 1);
9794                 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9795         }
9796
9797         let _ = nodes[0].node.get_and_clear_pending_msg_events();
9798         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9799         added_monitors.clear();
9800 }
9801
9802 #[test]
9803 fn test_max_dust_htlc_exposure() {
9804         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9805         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9806         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9807         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9808         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9809         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9810         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9811         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9812         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9813         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9814         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9815         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
9816 }
9817
9818 #[test]
9819 fn test_non_final_funding_tx() {
9820         let chanmon_cfgs = create_chanmon_cfgs(2);
9821         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9822         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9823         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9824
9825         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9826         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9827         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9828         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9829         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9830
9831         let best_height = nodes[0].node.best_block.read().unwrap().height();
9832
9833         let chan_id = *nodes[0].network_chan_count.borrow();
9834         let events = nodes[0].node.get_and_clear_pending_events();
9835         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9836         assert_eq!(events.len(), 1);
9837         let mut tx = match events[0] {
9838                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9839                         // Timelock the transaction _beyond_ the best client height + 2.
9840                         Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 3), input: vec![input], output: vec![TxOut {
9841                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9842                         }]}
9843                 },
9844                 _ => panic!("Unexpected event"),
9845         };
9846         // Transaction should fail as it's evaluated as non-final for propagation.
9847         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9848                 Err(APIError::APIMisuseError { err }) => {
9849                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9850                 },
9851                 _ => panic!()
9852         }
9853
9854         // However, transaction should be accepted if it's in a +2 headroom from best block.
9855         tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9856         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9857         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9858 }
9859
9860 #[test]
9861 fn accept_busted_but_better_fee() {
9862         // If a peer sends us a fee update that is too low, but higher than our previous channel
9863         // feerate, we should accept it. In the future we may want to consider closing the channel
9864         // later, but for now we only accept the update.
9865         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9866         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9867         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9868         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9869
9870         create_chan_between_nodes(&nodes[0], &nodes[1]);
9871
9872         // Set nodes[1] to expect 5,000 sat/kW.
9873         {
9874                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9875                 *feerate_lock = 5000;
9876         }
9877
9878         // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9879         {
9880                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9881                 *feerate_lock = 1000;
9882         }
9883         nodes[0].node.timer_tick_occurred();
9884         check_added_monitors!(nodes[0], 1);
9885
9886         let events = nodes[0].node.get_and_clear_pending_msg_events();
9887         assert_eq!(events.len(), 1);
9888         match events[0] {
9889                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9890                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9891                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9892                 },
9893                 _ => panic!("Unexpected event"),
9894         };
9895
9896         // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9897         // it.
9898         {
9899                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9900                 *feerate_lock = 2000;
9901         }
9902         nodes[0].node.timer_tick_occurred();
9903         check_added_monitors!(nodes[0], 1);
9904
9905         let events = nodes[0].node.get_and_clear_pending_msg_events();
9906         assert_eq!(events.len(), 1);
9907         match events[0] {
9908                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9909                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9910                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9911                 },
9912                 _ => panic!("Unexpected event"),
9913         };
9914
9915         // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9916         // channel.
9917         {
9918                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9919                 *feerate_lock = 1000;
9920         }
9921         nodes[0].node.timer_tick_occurred();
9922         check_added_monitors!(nodes[0], 1);
9923
9924         let events = nodes[0].node.get_and_clear_pending_msg_events();
9925         assert_eq!(events.len(), 1);
9926         match events[0] {
9927                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9928                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9929                         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9930                                 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() });
9931                         check_closed_broadcast!(nodes[1], true);
9932                         check_added_monitors!(nodes[1], 1);
9933                 },
9934                 _ => panic!("Unexpected event"),
9935         };
9936 }
9937
9938 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9939         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9940         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9941         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9942         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9943         let min_final_cltv_expiry_delta = 120;
9944         let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9945                 min_final_cltv_expiry_delta - 2 };
9946         let recv_value = 100_000;
9947
9948         create_chan_between_nodes(&nodes[0], &nodes[1]);
9949
9950         let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
9951         let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
9952                 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
9953                         Some(recv_value), Some(min_final_cltv_expiry_delta));
9954                 (payment_hash, payment_preimage, payment_secret)
9955         } else {
9956                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
9957                 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
9958         };
9959         let route = get_route!(nodes[0], payment_parameters, recv_value, final_cltv_expiry_delta as u32).unwrap();
9960         nodes[0].node.send_payment_with_route(&route, payment_hash,
9961                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9962         check_added_monitors!(nodes[0], 1);
9963         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9964         assert_eq!(events.len(), 1);
9965         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9966         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9967         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9968         expect_pending_htlcs_forwardable!(nodes[1]);
9969
9970         if valid_delta {
9971                 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
9972                         None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
9973
9974                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9975         } else {
9976                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9977
9978                 check_added_monitors!(nodes[1], 1);
9979
9980                 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9981                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
9982                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
9983
9984                 expect_payment_failed!(nodes[0], payment_hash, true);
9985         }
9986 }
9987
9988 #[test]
9989 fn test_payment_with_custom_min_cltv_expiry_delta() {
9990         do_payment_with_custom_min_final_cltv_expiry(false, false);
9991         do_payment_with_custom_min_final_cltv_expiry(false, true);
9992         do_payment_with_custom_min_final_cltv_expiry(true, false);
9993         do_payment_with_custom_min_final_cltv_expiry(true, true);
9994 }