]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/ln/functional_tests.rs
Persist scorer upon update based on event handling
[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, ENABLE_GOSSIP_TICKS, DISABLE_GOSSIP_TICKS, 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::{Path, 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![Path { hops, blinded_tail: None }], 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![Path { hops, blinded_tail: None }], 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..50 {
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); // 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].hops.last_mut().unwrap().fee_msat += 1;
1835                 assert!(route.paths[0].hops.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_htlc_timeout() {
2394         // Test justice txn built on revoked HTLC-Timeout 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         // Create some new channels:
2411         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2412
2413         // A pending HTLC which will be revoked:
2414         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2415         // Get the will-be-revoked local txn from nodes[0]
2416         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2417         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2418         assert_eq!(revoked_local_txn[0].input.len(), 1);
2419         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2420         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2421         assert_eq!(revoked_local_txn[1].input.len(), 1);
2422         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2423         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2424         // Revoke the old state
2425         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2426
2427         {
2428                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2429                 {
2430                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2431                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2432                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2433                         check_spends!(node_txn[0], revoked_local_txn[0]);
2434                         node_txn.swap_remove(0);
2435                 }
2436                 check_added_monitors!(nodes[1], 1);
2437                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2438                 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2439
2440                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2441                 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2442                 // Verify broadcast of revoked HTLC-timeout
2443                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2444                 check_added_monitors!(nodes[0], 1);
2445                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2446                 // Broadcast revoked HTLC-timeout on node 1
2447                 mine_transaction(&nodes[1], &node_txn[1]);
2448                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2449         }
2450         get_announce_close_broadcast_events(&nodes, 0, 1);
2451         assert_eq!(nodes[0].node.list_channels().len(), 0);
2452         assert_eq!(nodes[1].node.list_channels().len(), 0);
2453 }
2454
2455 #[test]
2456 fn test_justice_tx_htlc_success() {
2457         // Test justice txn built on revoked HTLC-Success tx, against both sides
2458         let mut alice_config = UserConfig::default();
2459         alice_config.channel_handshake_config.announced_channel = true;
2460         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2461         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2462         let mut bob_config = UserConfig::default();
2463         bob_config.channel_handshake_config.announced_channel = true;
2464         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2465         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2466         let user_cfgs = [Some(alice_config), Some(bob_config)];
2467         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2468         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2469         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2470         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2471         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2472         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2473         // Create some new channels:
2474         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2475
2476         // A pending HTLC which will be revoked:
2477         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2478         // Get the will-be-revoked local txn from B
2479         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2480         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2481         assert_eq!(revoked_local_txn[0].input.len(), 1);
2482         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2483         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2484         // Revoke the old state
2485         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2486         {
2487                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2488                 {
2489                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2490                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2491                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2492
2493                         check_spends!(node_txn[0], revoked_local_txn[0]);
2494                         node_txn.swap_remove(0);
2495                 }
2496                 check_added_monitors!(nodes[0], 1);
2497                 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2498
2499                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2500                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2501                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2502                 check_added_monitors!(nodes[1], 1);
2503                 mine_transaction(&nodes[0], &node_txn[1]);
2504                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2505                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2506         }
2507         get_announce_close_broadcast_events(&nodes, 0, 1);
2508         assert_eq!(nodes[0].node.list_channels().len(), 0);
2509         assert_eq!(nodes[1].node.list_channels().len(), 0);
2510 }
2511
2512 #[test]
2513 fn revoked_output_claim() {
2514         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2515         // transaction is broadcast by its counterparty
2516         let chanmon_cfgs = create_chanmon_cfgs(2);
2517         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2518         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2519         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2520         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2521         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2522         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2523         assert_eq!(revoked_local_txn.len(), 1);
2524         // Only output is the full channel value back to nodes[0]:
2525         assert_eq!(revoked_local_txn[0].output.len(), 1);
2526         // Send a payment through, updating everyone's latest commitment txn
2527         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2528
2529         // Inform nodes[1] that nodes[0] broadcast a stale tx
2530         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2531         check_added_monitors!(nodes[1], 1);
2532         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2533         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2534         assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2535
2536         check_spends!(node_txn[0], revoked_local_txn[0]);
2537
2538         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2539         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2540         get_announce_close_broadcast_events(&nodes, 0, 1);
2541         check_added_monitors!(nodes[0], 1);
2542         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2543 }
2544
2545 #[test]
2546 fn claim_htlc_outputs_shared_tx() {
2547         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2548         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2549         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2550         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2551         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2552         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2553
2554         // Create some new channel:
2555         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2556
2557         // Rebalance the network to generate htlc in the two directions
2558         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2559         // 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
2560         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2561         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2562
2563         // Get the will-be-revoked local txn from node[0]
2564         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2565         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2566         assert_eq!(revoked_local_txn[0].input.len(), 1);
2567         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2568         assert_eq!(revoked_local_txn[1].input.len(), 1);
2569         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2570         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2571         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2572
2573         //Revoke the old state
2574         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2575
2576         {
2577                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2578                 check_added_monitors!(nodes[0], 1);
2579                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2580                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2581                 check_added_monitors!(nodes[1], 1);
2582                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2583                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2584                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2585
2586                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2587                 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2588
2589                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2590                 check_spends!(node_txn[0], revoked_local_txn[0]);
2591
2592                 let mut witness_lens = BTreeSet::new();
2593                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2594                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2595                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2596                 assert_eq!(witness_lens.len(), 3);
2597                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2598                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2599                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2600
2601                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2602                 // ANTI_REORG_DELAY confirmations.
2603                 mine_transaction(&nodes[1], &node_txn[0]);
2604                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2605                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2606         }
2607         get_announce_close_broadcast_events(&nodes, 0, 1);
2608         assert_eq!(nodes[0].node.list_channels().len(), 0);
2609         assert_eq!(nodes[1].node.list_channels().len(), 0);
2610 }
2611
2612 #[test]
2613 fn claim_htlc_outputs_single_tx() {
2614         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2615         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2616         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2617         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2618         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2619         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2620
2621         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2622
2623         // Rebalance the network to generate htlc in the two directions
2624         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2625         // 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
2626         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2627         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2628         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2629
2630         // Get the will-be-revoked local txn from node[0]
2631         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2632
2633         //Revoke the old state
2634         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2635
2636         {
2637                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2638                 check_added_monitors!(nodes[0], 1);
2639                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2640                 check_added_monitors!(nodes[1], 1);
2641                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2642                 let mut events = nodes[0].node.get_and_clear_pending_events();
2643                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2644                 match events.last().unwrap() {
2645                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2646                         _ => panic!("Unexpected event"),
2647                 }
2648
2649                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2650                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2651
2652                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcast();
2653
2654                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2655                 assert_eq!(node_txn[0].input.len(), 1);
2656                 check_spends!(node_txn[0], chan_1.3);
2657                 assert_eq!(node_txn[1].input.len(), 1);
2658                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2659                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2660                 check_spends!(node_txn[1], node_txn[0]);
2661
2662                 // Filter out any non justice transactions.
2663                 node_txn.retain(|tx| tx.input[0].previous_output.txid == revoked_local_txn[0].txid());
2664                 assert!(node_txn.len() > 3);
2665
2666                 assert_eq!(node_txn[0].input.len(), 1);
2667                 assert_eq!(node_txn[1].input.len(), 1);
2668                 assert_eq!(node_txn[2].input.len(), 1);
2669
2670                 check_spends!(node_txn[0], revoked_local_txn[0]);
2671                 check_spends!(node_txn[1], revoked_local_txn[0]);
2672                 check_spends!(node_txn[2], revoked_local_txn[0]);
2673
2674                 let mut witness_lens = BTreeSet::new();
2675                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2676                 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2677                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2678                 assert_eq!(witness_lens.len(), 3);
2679                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2680                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2681                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2682
2683                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2684                 // ANTI_REORG_DELAY confirmations.
2685                 mine_transaction(&nodes[1], &node_txn[0]);
2686                 mine_transaction(&nodes[1], &node_txn[1]);
2687                 mine_transaction(&nodes[1], &node_txn[2]);
2688                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2689                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2690         }
2691         get_announce_close_broadcast_events(&nodes, 0, 1);
2692         assert_eq!(nodes[0].node.list_channels().len(), 0);
2693         assert_eq!(nodes[1].node.list_channels().len(), 0);
2694 }
2695
2696 #[test]
2697 fn test_htlc_on_chain_success() {
2698         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2699         // the preimage backward accordingly. So here we test that ChannelManager is
2700         // broadcasting the right event to other nodes in payment path.
2701         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2702         // A --------------------> B ----------------------> C (preimage)
2703         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2704         // commitment transaction was broadcast.
2705         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2706         // towards B.
2707         // B should be able to claim via preimage if A then broadcasts its local tx.
2708         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2709         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2710         // PaymentSent event).
2711
2712         let chanmon_cfgs = create_chanmon_cfgs(3);
2713         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2714         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2715         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2716
2717         // Create some initial channels
2718         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2719         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2720
2721         // Ensure all nodes are at the same height
2722         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2723         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2724         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2725         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2726
2727         // Rebalance the network a bit by relaying one payment through all the channels...
2728         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2729         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2730
2731         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2732         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2733
2734         // Broadcast legit commitment tx from C on B's chain
2735         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2736         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2737         assert_eq!(commitment_tx.len(), 1);
2738         check_spends!(commitment_tx[0], chan_2.3);
2739         nodes[2].node.claim_funds(our_payment_preimage);
2740         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2741         nodes[2].node.claim_funds(our_payment_preimage_2);
2742         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2743         check_added_monitors!(nodes[2], 2);
2744         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2745         assert!(updates.update_add_htlcs.is_empty());
2746         assert!(updates.update_fail_htlcs.is_empty());
2747         assert!(updates.update_fail_malformed_htlcs.is_empty());
2748         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2749
2750         mine_transaction(&nodes[2], &commitment_tx[0]);
2751         check_closed_broadcast!(nodes[2], true);
2752         check_added_monitors!(nodes[2], 1);
2753         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2754         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2755         assert_eq!(node_txn.len(), 2);
2756         check_spends!(node_txn[0], commitment_tx[0]);
2757         check_spends!(node_txn[1], commitment_tx[0]);
2758         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2759         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2760         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2761         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2762         assert_eq!(node_txn[0].lock_time.0, 0);
2763         assert_eq!(node_txn[1].lock_time.0, 0);
2764
2765         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2766         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2767         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone(), node_txn[1].clone()]});
2768         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2769         {
2770                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2771                 assert_eq!(added_monitors.len(), 1);
2772                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2773                 added_monitors.clear();
2774         }
2775         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2776         assert_eq!(forwarded_events.len(), 3);
2777         match forwarded_events[0] {
2778                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2779                 _ => panic!("Unexpected event"),
2780         }
2781         let chan_id = Some(chan_1.2);
2782         match forwarded_events[1] {
2783                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2784                         assert_eq!(fee_earned_msat, Some(1000));
2785                         assert_eq!(prev_channel_id, chan_id);
2786                         assert_eq!(claim_from_onchain_tx, true);
2787                         assert_eq!(next_channel_id, Some(chan_2.2));
2788                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2789                 },
2790                 _ => panic!()
2791         }
2792         match forwarded_events[2] {
2793                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2794                         assert_eq!(fee_earned_msat, Some(1000));
2795                         assert_eq!(prev_channel_id, chan_id);
2796                         assert_eq!(claim_from_onchain_tx, true);
2797                         assert_eq!(next_channel_id, Some(chan_2.2));
2798                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2799                 },
2800                 _ => panic!()
2801         }
2802         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2803         {
2804                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2805                 assert_eq!(added_monitors.len(), 2);
2806                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2807                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2808                 added_monitors.clear();
2809         }
2810         assert_eq!(events.len(), 3);
2811
2812         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2813         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2814
2815         match nodes_2_event {
2816                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2817                 _ => panic!("Unexpected event"),
2818         }
2819
2820         match nodes_0_event {
2821                 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, .. } } => {
2822                         assert!(update_add_htlcs.is_empty());
2823                         assert!(update_fail_htlcs.is_empty());
2824                         assert_eq!(update_fulfill_htlcs.len(), 1);
2825                         assert!(update_fail_malformed_htlcs.is_empty());
2826                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2827                 },
2828                 _ => panic!("Unexpected event"),
2829         };
2830
2831         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2832         match events[0] {
2833                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2834                 _ => panic!("Unexpected event"),
2835         }
2836
2837         macro_rules! check_tx_local_broadcast {
2838                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2839                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2840                         assert_eq!(node_txn.len(), 2);
2841                         // Node[1]: 2 * HTLC-timeout tx
2842                         // Node[0]: 2 * HTLC-timeout tx
2843                         check_spends!(node_txn[0], $commitment_tx);
2844                         check_spends!(node_txn[1], $commitment_tx);
2845                         assert_ne!(node_txn[0].lock_time.0, 0);
2846                         assert_ne!(node_txn[1].lock_time.0, 0);
2847                         if $htlc_offered {
2848                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2849                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2850                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2851                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2852                         } else {
2853                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2854                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2855                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2856                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2857                         }
2858                         node_txn.clear();
2859                 } }
2860         }
2861         // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2862         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2863
2864         // Broadcast legit commitment tx from A on B's chain
2865         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2866         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2867         check_spends!(node_a_commitment_tx[0], chan_1.3);
2868         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2869         check_closed_broadcast!(nodes[1], true);
2870         check_added_monitors!(nodes[1], 1);
2871         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2872         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2873         assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2874         let commitment_spend =
2875                 if node_txn.len() == 1 {
2876                         &node_txn[0]
2877                 } else {
2878                         // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2879                         // FullBlockViaListen
2880                         if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2881                                 check_spends!(node_txn[1], commitment_tx[0]);
2882                                 check_spends!(node_txn[2], commitment_tx[0]);
2883                                 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2884                                 &node_txn[0]
2885                         } else {
2886                                 check_spends!(node_txn[0], commitment_tx[0]);
2887                                 check_spends!(node_txn[1], commitment_tx[0]);
2888                                 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2889                                 &node_txn[2]
2890                         }
2891                 };
2892
2893         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2894         assert_eq!(commitment_spend.input.len(), 2);
2895         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2896         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2897         assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1);
2898         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2899         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2900         // we already checked the same situation with A.
2901
2902         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2903         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2904         connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2905         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
2906         check_closed_broadcast!(nodes[0], true);
2907         check_added_monitors!(nodes[0], 1);
2908         let events = nodes[0].node.get_and_clear_pending_events();
2909         assert_eq!(events.len(), 5);
2910         let mut first_claimed = false;
2911         for event in events {
2912                 match event {
2913                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2914                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2915                                         assert!(!first_claimed);
2916                                         first_claimed = true;
2917                                 } else {
2918                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2919                                         assert_eq!(payment_hash, payment_hash_2);
2920                                 }
2921                         },
2922                         Event::PaymentPathSuccessful { .. } => {},
2923                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2924                         _ => panic!("Unexpected event"),
2925                 }
2926         }
2927         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
2928 }
2929
2930 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2931         // Test that in case of a unilateral close onchain, we detect the state of output and
2932         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2933         // broadcasting the right event to other nodes in payment path.
2934         // A ------------------> B ----------------------> C (timeout)
2935         //    B's commitment tx                 C's commitment tx
2936         //            \                                  \
2937         //         B's HTLC timeout tx               B's timeout tx
2938
2939         let chanmon_cfgs = create_chanmon_cfgs(3);
2940         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2941         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2942         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2943         *nodes[0].connect_style.borrow_mut() = connect_style;
2944         *nodes[1].connect_style.borrow_mut() = connect_style;
2945         *nodes[2].connect_style.borrow_mut() = connect_style;
2946
2947         // Create some intial channels
2948         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2949         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2950
2951         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2952         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2953         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2954
2955         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2956
2957         // Broadcast legit commitment tx from C on B's chain
2958         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2959         check_spends!(commitment_tx[0], chan_2.3);
2960         nodes[2].node.fail_htlc_backwards(&payment_hash);
2961         check_added_monitors!(nodes[2], 0);
2962         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2963         check_added_monitors!(nodes[2], 1);
2964
2965         let events = nodes[2].node.get_and_clear_pending_msg_events();
2966         assert_eq!(events.len(), 1);
2967         match events[0] {
2968                 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, .. } } => {
2969                         assert!(update_add_htlcs.is_empty());
2970                         assert!(!update_fail_htlcs.is_empty());
2971                         assert!(update_fulfill_htlcs.is_empty());
2972                         assert!(update_fail_malformed_htlcs.is_empty());
2973                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2974                 },
2975                 _ => panic!("Unexpected event"),
2976         };
2977         mine_transaction(&nodes[2], &commitment_tx[0]);
2978         check_closed_broadcast!(nodes[2], true);
2979         check_added_monitors!(nodes[2], 1);
2980         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2981         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2982         assert_eq!(node_txn.len(), 0);
2983
2984         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2985         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2986         mine_transaction(&nodes[1], &commitment_tx[0]);
2987         check_closed_event(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false);
2988         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2989         let timeout_tx = {
2990                 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
2991                 if nodes[1].connect_style.borrow().skips_blocks() {
2992                         assert_eq!(txn.len(), 1);
2993                 } else {
2994                         assert_eq!(txn.len(), 3); // Two extra fee bumps for timeout transaction
2995                 }
2996                 txn.iter().for_each(|tx| check_spends!(tx, commitment_tx[0]));
2997                 assert_eq!(txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2998                 txn.remove(0)
2999         };
3000
3001         mine_transaction(&nodes[1], &timeout_tx);
3002         check_added_monitors!(nodes[1], 1);
3003         check_closed_broadcast!(nodes[1], true);
3004
3005         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3006
3007         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 }]);
3008         check_added_monitors!(nodes[1], 1);
3009         let events = nodes[1].node.get_and_clear_pending_msg_events();
3010         assert_eq!(events.len(), 1);
3011         match events[0] {
3012                 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, .. } } => {
3013                         assert!(update_add_htlcs.is_empty());
3014                         assert!(!update_fail_htlcs.is_empty());
3015                         assert!(update_fulfill_htlcs.is_empty());
3016                         assert!(update_fail_malformed_htlcs.is_empty());
3017                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3018                 },
3019                 _ => panic!("Unexpected event"),
3020         };
3021
3022         // Broadcast legit commitment tx from B on A's chain
3023         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3024         check_spends!(commitment_tx[0], chan_1.3);
3025
3026         mine_transaction(&nodes[0], &commitment_tx[0]);
3027         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3028
3029         check_closed_broadcast!(nodes[0], true);
3030         check_added_monitors!(nodes[0], 1);
3031         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
3032         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
3033         assert_eq!(node_txn.len(), 1);
3034         check_spends!(node_txn[0], commitment_tx[0]);
3035         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3036 }
3037
3038 #[test]
3039 fn test_htlc_on_chain_timeout() {
3040         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3041         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3042         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3043 }
3044
3045 #[test]
3046 fn test_simple_commitment_revoked_fail_backward() {
3047         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3048         // and fail backward accordingly.
3049
3050         let chanmon_cfgs = create_chanmon_cfgs(3);
3051         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3052         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3053         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3054
3055         // Create some initial channels
3056         create_announced_chan_between_nodes(&nodes, 0, 1);
3057         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3058
3059         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3060         // Get the will-be-revoked local txn from nodes[2]
3061         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3062         // Revoke the old state
3063         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3064
3065         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3066
3067         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3068         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3069         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3070         check_added_monitors!(nodes[1], 1);
3071         check_closed_broadcast!(nodes[1], true);
3072
3073         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 }]);
3074         check_added_monitors!(nodes[1], 1);
3075         let events = nodes[1].node.get_and_clear_pending_msg_events();
3076         assert_eq!(events.len(), 1);
3077         match events[0] {
3078                 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, .. } } => {
3079                         assert!(update_add_htlcs.is_empty());
3080                         assert_eq!(update_fail_htlcs.len(), 1);
3081                         assert!(update_fulfill_htlcs.is_empty());
3082                         assert!(update_fail_malformed_htlcs.is_empty());
3083                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3084
3085                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3086                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3087                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3088                 },
3089                 _ => panic!("Unexpected event"),
3090         }
3091 }
3092
3093 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3094         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3095         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3096         // commitment transaction anymore.
3097         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3098         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3099         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3100         // technically disallowed and we should probably handle it reasonably.
3101         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3102         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3103         // transactions:
3104         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3105         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3106         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3107         //   and once they revoke the previous commitment transaction (allowing us to send a new
3108         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3109         let chanmon_cfgs = create_chanmon_cfgs(3);
3110         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3111         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3112         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3113
3114         // Create some initial channels
3115         create_announced_chan_between_nodes(&nodes, 0, 1);
3116         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3117
3118         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 });
3119         // Get the will-be-revoked local txn from nodes[2]
3120         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3121         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3122         // Revoke the old state
3123         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3124
3125         let value = if use_dust {
3126                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3127                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3128                 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3129                         .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3130         } else { 3000000 };
3131
3132         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3133         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3134         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3135
3136         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3137         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3138         check_added_monitors!(nodes[2], 1);
3139         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3140         assert!(updates.update_add_htlcs.is_empty());
3141         assert!(updates.update_fulfill_htlcs.is_empty());
3142         assert!(updates.update_fail_malformed_htlcs.is_empty());
3143         assert_eq!(updates.update_fail_htlcs.len(), 1);
3144         assert!(updates.update_fee.is_none());
3145         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3146         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3147         // Drop the last RAA from 3 -> 2
3148
3149         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3150         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3151         check_added_monitors!(nodes[2], 1);
3152         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3153         assert!(updates.update_add_htlcs.is_empty());
3154         assert!(updates.update_fulfill_htlcs.is_empty());
3155         assert!(updates.update_fail_malformed_htlcs.is_empty());
3156         assert_eq!(updates.update_fail_htlcs.len(), 1);
3157         assert!(updates.update_fee.is_none());
3158         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3159         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3160         check_added_monitors!(nodes[1], 1);
3161         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3162         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3163         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3164         check_added_monitors!(nodes[2], 1);
3165
3166         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3167         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3168         check_added_monitors!(nodes[2], 1);
3169         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3170         assert!(updates.update_add_htlcs.is_empty());
3171         assert!(updates.update_fulfill_htlcs.is_empty());
3172         assert!(updates.update_fail_malformed_htlcs.is_empty());
3173         assert_eq!(updates.update_fail_htlcs.len(), 1);
3174         assert!(updates.update_fee.is_none());
3175         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3176         // At this point first_payment_hash has dropped out of the latest two commitment
3177         // transactions that nodes[1] is tracking...
3178         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3179         check_added_monitors!(nodes[1], 1);
3180         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3181         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3182         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3183         check_added_monitors!(nodes[2], 1);
3184
3185         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3186         // on nodes[2]'s RAA.
3187         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3188         nodes[1].node.send_payment_with_route(&route, fourth_payment_hash,
3189                 RecipientOnionFields::secret_only(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3190         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3191         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3192         check_added_monitors!(nodes[1], 0);
3193
3194         if deliver_bs_raa {
3195                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3196                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3197                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3198                 check_added_monitors!(nodes[1], 1);
3199                 let events = nodes[1].node.get_and_clear_pending_events();
3200                 assert_eq!(events.len(), 2);
3201                 match events[0] {
3202                         Event::PendingHTLCsForwardable { .. } => { },
3203                         _ => panic!("Unexpected event"),
3204                 };
3205                 match events[1] {
3206                         Event::HTLCHandlingFailed { .. } => { },
3207                         _ => panic!("Unexpected event"),
3208                 }
3209                 // Deliberately don't process the pending fail-back so they all fail back at once after
3210                 // block connection just like the !deliver_bs_raa case
3211         }
3212
3213         let mut failed_htlcs = HashSet::new();
3214         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3215
3216         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3217         check_added_monitors!(nodes[1], 1);
3218         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3219
3220         let events = nodes[1].node.get_and_clear_pending_events();
3221         assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3222         match events[0] {
3223                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3224                 _ => panic!("Unexepected event"),
3225         }
3226         match events[1] {
3227                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3228                         assert_eq!(*payment_hash, fourth_payment_hash);
3229                 },
3230                 _ => panic!("Unexpected event"),
3231         }
3232         match events[2] {
3233                 Event::PaymentFailed { ref payment_hash, .. } => {
3234                         assert_eq!(*payment_hash, fourth_payment_hash);
3235                 },
3236                 _ => panic!("Unexpected event"),
3237         }
3238
3239         nodes[1].node.process_pending_htlc_forwards();
3240         check_added_monitors!(nodes[1], 1);
3241
3242         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3243         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3244
3245         if deliver_bs_raa {
3246                 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3247                 match nodes_2_event {
3248                         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, .. } } => {
3249                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3250                                 assert_eq!(update_add_htlcs.len(), 1);
3251                                 assert!(update_fulfill_htlcs.is_empty());
3252                                 assert!(update_fail_htlcs.is_empty());
3253                                 assert!(update_fail_malformed_htlcs.is_empty());
3254                         },
3255                         _ => panic!("Unexpected event"),
3256                 }
3257         }
3258
3259         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3260         match nodes_2_event {
3261                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3262                         assert_eq!(channel_id, chan_2.2);
3263                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3264                 },
3265                 _ => panic!("Unexpected event"),
3266         }
3267
3268         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3269         match nodes_0_event {
3270                 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, .. } } => {
3271                         assert!(update_add_htlcs.is_empty());
3272                         assert_eq!(update_fail_htlcs.len(), 3);
3273                         assert!(update_fulfill_htlcs.is_empty());
3274                         assert!(update_fail_malformed_htlcs.is_empty());
3275                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3276
3277                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3278                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3279                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3280
3281                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3282
3283                         let events = nodes[0].node.get_and_clear_pending_events();
3284                         assert_eq!(events.len(), 6);
3285                         match events[0] {
3286                                 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3287                                         assert!(failed_htlcs.insert(payment_hash.0));
3288                                         // If we delivered B's RAA we got an unknown preimage error, not something
3289                                         // that we should update our routing table for.
3290                                         if !deliver_bs_raa {
3291                                                 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3292                                         }
3293                                 },
3294                                 _ => panic!("Unexpected event"),
3295                         }
3296                         match events[1] {
3297                                 Event::PaymentFailed { ref payment_hash, .. } => {
3298                                         assert_eq!(*payment_hash, first_payment_hash);
3299                                 },
3300                                 _ => panic!("Unexpected event"),
3301                         }
3302                         match events[2] {
3303                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3304                                         assert!(failed_htlcs.insert(payment_hash.0));
3305                                 },
3306                                 _ => panic!("Unexpected event"),
3307                         }
3308                         match events[3] {
3309                                 Event::PaymentFailed { ref payment_hash, .. } => {
3310                                         assert_eq!(*payment_hash, second_payment_hash);
3311                                 },
3312                                 _ => panic!("Unexpected event"),
3313                         }
3314                         match events[4] {
3315                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3316                                         assert!(failed_htlcs.insert(payment_hash.0));
3317                                 },
3318                                 _ => panic!("Unexpected event"),
3319                         }
3320                         match events[5] {
3321                                 Event::PaymentFailed { ref payment_hash, .. } => {
3322                                         assert_eq!(*payment_hash, third_payment_hash);
3323                                 },
3324                                 _ => panic!("Unexpected event"),
3325                         }
3326                 },
3327                 _ => panic!("Unexpected event"),
3328         }
3329
3330         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3331         match events[0] {
3332                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3333                 _ => panic!("Unexpected event"),
3334         }
3335
3336         assert!(failed_htlcs.contains(&first_payment_hash.0));
3337         assert!(failed_htlcs.contains(&second_payment_hash.0));
3338         assert!(failed_htlcs.contains(&third_payment_hash.0));
3339 }
3340
3341 #[test]
3342 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3343         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3344         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3345         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3346         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3347 }
3348
3349 #[test]
3350 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3351         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3352         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3353         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3354         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3355 }
3356
3357 #[test]
3358 fn fail_backward_pending_htlc_upon_channel_failure() {
3359         let chanmon_cfgs = create_chanmon_cfgs(2);
3360         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3361         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3362         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3363         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3364
3365         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3366         {
3367                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3368                 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret),
3369                         PaymentId(payment_hash.0)).unwrap();
3370                 check_added_monitors!(nodes[0], 1);
3371
3372                 let payment_event = {
3373                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3374                         assert_eq!(events.len(), 1);
3375                         SendEvent::from_event(events.remove(0))
3376                 };
3377                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3378                 assert_eq!(payment_event.msgs.len(), 1);
3379         }
3380
3381         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3382         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3383         {
3384                 nodes[0].node.send_payment_with_route(&route, failed_payment_hash,
3385                         RecipientOnionFields::secret_only(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3386                 check_added_monitors!(nodes[0], 0);
3387
3388                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3389         }
3390
3391         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3392         {
3393                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3394
3395                 let secp_ctx = Secp256k1::new();
3396                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3397                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3398                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(
3399                         &route.paths[0], 50_000, RecipientOnionFields::secret_only(payment_secret), current_height, &None).unwrap();
3400                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3401                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3402
3403                 // Send a 0-msat update_add_htlc to fail the channel.
3404                 let update_add_htlc = msgs::UpdateAddHTLC {
3405                         channel_id: chan.2,
3406                         htlc_id: 0,
3407                         amount_msat: 0,
3408                         payment_hash,
3409                         cltv_expiry,
3410                         onion_routing_packet,
3411                 };
3412                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3413         }
3414         let events = nodes[0].node.get_and_clear_pending_events();
3415         assert_eq!(events.len(), 3);
3416         // Check that Alice fails backward the pending HTLC from the second payment.
3417         match events[0] {
3418                 Event::PaymentPathFailed { payment_hash, .. } => {
3419                         assert_eq!(payment_hash, failed_payment_hash);
3420                 },
3421                 _ => panic!("Unexpected event"),
3422         }
3423         match events[1] {
3424                 Event::PaymentFailed { payment_hash, .. } => {
3425                         assert_eq!(payment_hash, failed_payment_hash);
3426                 },
3427                 _ => panic!("Unexpected event"),
3428         }
3429         match events[2] {
3430                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3431                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3432                 },
3433                 _ => panic!("Unexpected event {:?}", events[1]),
3434         }
3435         check_closed_broadcast!(nodes[0], true);
3436         check_added_monitors!(nodes[0], 1);
3437 }
3438
3439 #[test]
3440 fn test_htlc_ignore_latest_remote_commitment() {
3441         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3442         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3443         let chanmon_cfgs = create_chanmon_cfgs(2);
3444         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3445         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3446         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3447         if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3448                 // We rely on the ability to connect a block redundantly, which isn't allowed via
3449                 // `chain::Listen`, so we never run the test if we randomly get assigned that
3450                 // connect_style.
3451                 return;
3452         }
3453         create_announced_chan_between_nodes(&nodes, 0, 1);
3454
3455         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3456         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3457         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3458         check_closed_broadcast!(nodes[0], true);
3459         check_added_monitors!(nodes[0], 1);
3460         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3461
3462         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3463         assert_eq!(node_txn.len(), 3);
3464         assert_eq!(node_txn[0].txid(), node_txn[1].txid());
3465
3466         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
3467         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3468         check_closed_broadcast!(nodes[1], true);
3469         check_added_monitors!(nodes[1], 1);
3470         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3471
3472         // Duplicate the connect_block call since this may happen due to other listeners
3473         // registering new transactions
3474         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3475 }
3476
3477 #[test]
3478 fn test_force_close_fail_back() {
3479         // Check which HTLCs are failed-backwards on channel force-closure
3480         let chanmon_cfgs = create_chanmon_cfgs(3);
3481         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3482         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3483         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3484         create_announced_chan_between_nodes(&nodes, 0, 1);
3485         create_announced_chan_between_nodes(&nodes, 1, 2);
3486
3487         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3488
3489         let mut payment_event = {
3490                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3491                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3492                 check_added_monitors!(nodes[0], 1);
3493
3494                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3495                 assert_eq!(events.len(), 1);
3496                 SendEvent::from_event(events.remove(0))
3497         };
3498
3499         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3500         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3501
3502         expect_pending_htlcs_forwardable!(nodes[1]);
3503
3504         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3505         assert_eq!(events_2.len(), 1);
3506         payment_event = SendEvent::from_event(events_2.remove(0));
3507         assert_eq!(payment_event.msgs.len(), 1);
3508
3509         check_added_monitors!(nodes[1], 1);
3510         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3511         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3512         check_added_monitors!(nodes[2], 1);
3513         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3514
3515         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3516         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3517         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3518
3519         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3520         check_closed_broadcast!(nodes[2], true);
3521         check_added_monitors!(nodes[2], 1);
3522         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3523         let tx = {
3524                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3525                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3526                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3527                 // back to nodes[1] upon timeout otherwise.
3528                 assert_eq!(node_txn.len(), 1);
3529                 node_txn.remove(0)
3530         };
3531
3532         mine_transaction(&nodes[1], &tx);
3533
3534         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3535         check_closed_broadcast!(nodes[1], true);
3536         check_added_monitors!(nodes[1], 1);
3537         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3538
3539         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3540         {
3541                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3542                         .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);
3543         }
3544         mine_transaction(&nodes[2], &tx);
3545         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3546         assert_eq!(node_txn.len(), 1);
3547         assert_eq!(node_txn[0].input.len(), 1);
3548         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3549         assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3550         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3551
3552         check_spends!(node_txn[0], tx);
3553 }
3554
3555 #[test]
3556 fn test_dup_events_on_peer_disconnect() {
3557         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3558         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3559         // as we used to generate the event immediately upon receipt of the payment preimage in the
3560         // update_fulfill_htlc message.
3561
3562         let chanmon_cfgs = create_chanmon_cfgs(2);
3563         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3564         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3565         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3566         create_announced_chan_between_nodes(&nodes, 0, 1);
3567
3568         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3569
3570         nodes[1].node.claim_funds(payment_preimage);
3571         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3572         check_added_monitors!(nodes[1], 1);
3573         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3574         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3575         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3576
3577         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3578         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3579
3580         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3581         expect_payment_path_successful!(nodes[0]);
3582 }
3583
3584 #[test]
3585 fn test_peer_disconnected_before_funding_broadcasted() {
3586         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3587         // before the funding transaction has been broadcasted.
3588         let chanmon_cfgs = create_chanmon_cfgs(2);
3589         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3590         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3591         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3592
3593         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3594         // broadcasted, even though it's created by `nodes[0]`.
3595         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();
3596         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3597         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3598         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3599         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3600
3601         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3602         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3603
3604         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3605
3606         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3607         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3608
3609         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3610         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3611         // broadcasted.
3612         {
3613                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3614         }
3615
3616         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3617         // disconnected before the funding transaction was broadcasted.
3618         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3619         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3620
3621         check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3622         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3623 }
3624
3625 #[test]
3626 fn test_simple_peer_disconnect() {
3627         // Test that we can reconnect when there are no lost messages
3628         let chanmon_cfgs = create_chanmon_cfgs(3);
3629         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3630         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3631         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3632         create_announced_chan_between_nodes(&nodes, 0, 1);
3633         create_announced_chan_between_nodes(&nodes, 1, 2);
3634
3635         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3636         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3637         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3638
3639         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3640         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3641         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3642         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3643
3644         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3645         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3646         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3647
3648         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3649         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3650         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3651         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3652
3653         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3654         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3655
3656         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3657         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3658
3659         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3660         {
3661                 let events = nodes[0].node.get_and_clear_pending_events();
3662                 assert_eq!(events.len(), 4);
3663                 match events[0] {
3664                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3665                                 assert_eq!(payment_preimage, payment_preimage_3);
3666                                 assert_eq!(payment_hash, payment_hash_3);
3667                         },
3668                         _ => panic!("Unexpected event"),
3669                 }
3670                 match events[1] {
3671                         Event::PaymentPathSuccessful { .. } => {},
3672                         _ => panic!("Unexpected event"),
3673                 }
3674                 match events[2] {
3675                         Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3676                                 assert_eq!(payment_hash, payment_hash_5);
3677                                 assert!(payment_failed_permanently);
3678                         },
3679                         _ => panic!("Unexpected event"),
3680                 }
3681                 match events[3] {
3682                         Event::PaymentFailed { payment_hash, .. } => {
3683                                 assert_eq!(payment_hash, payment_hash_5);
3684                         },
3685                         _ => panic!("Unexpected event"),
3686                 }
3687         }
3688
3689         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3690         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3691 }
3692
3693 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3694         // Test that we can reconnect when in-flight HTLC updates get dropped
3695         let chanmon_cfgs = create_chanmon_cfgs(2);
3696         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3697         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3698         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3699
3700         let mut as_channel_ready = None;
3701         let channel_id = if messages_delivered == 0 {
3702                 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3703                 as_channel_ready = Some(channel_ready);
3704                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3705                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3706                 // it before the channel_reestablish message.
3707                 chan_id
3708         } else {
3709                 create_announced_chan_between_nodes(&nodes, 0, 1).2
3710         };
3711
3712         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3713
3714         let payment_event = {
3715                 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3716                         RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3717                 check_added_monitors!(nodes[0], 1);
3718
3719                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3720                 assert_eq!(events.len(), 1);
3721                 SendEvent::from_event(events.remove(0))
3722         };
3723         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3724
3725         if messages_delivered < 2 {
3726                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3727         } else {
3728                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3729                 if messages_delivered >= 3 {
3730                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3731                         check_added_monitors!(nodes[1], 1);
3732                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3733
3734                         if messages_delivered >= 4 {
3735                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3736                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3737                                 check_added_monitors!(nodes[0], 1);
3738
3739                                 if messages_delivered >= 5 {
3740                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3741                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3742                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3743                                         check_added_monitors!(nodes[0], 1);
3744
3745                                         if messages_delivered >= 6 {
3746                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3747                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3748                                                 check_added_monitors!(nodes[1], 1);
3749                                         }
3750                                 }
3751                         }
3752                 }
3753         }
3754
3755         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3756         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3757         if messages_delivered < 3 {
3758                 if simulate_broken_lnd {
3759                         // lnd has a long-standing bug where they send a channel_ready prior to a
3760                         // channel_reestablish if you reconnect prior to channel_ready time.
3761                         //
3762                         // Here we simulate that behavior, delivering a channel_ready immediately on
3763                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3764                         // in `reconnect_nodes` but we currently don't fail based on that.
3765                         //
3766                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3767                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3768                 }
3769                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3770                 // received on either side, both sides will need to resend them.
3771                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3772         } else if messages_delivered == 3 {
3773                 // nodes[0] still wants its RAA + commitment_signed
3774                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3775         } else if messages_delivered == 4 {
3776                 // nodes[0] still wants its commitment_signed
3777                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3778         } else if messages_delivered == 5 {
3779                 // nodes[1] still wants its final RAA
3780                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3781         } else if messages_delivered == 6 {
3782                 // Everything was delivered...
3783                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3784         }
3785
3786         let events_1 = nodes[1].node.get_and_clear_pending_events();
3787         if messages_delivered == 0 {
3788                 assert_eq!(events_1.len(), 2);
3789                 match events_1[0] {
3790                         Event::ChannelReady { .. } => { },
3791                         _ => panic!("Unexpected event"),
3792                 };
3793                 match events_1[1] {
3794                         Event::PendingHTLCsForwardable { .. } => { },
3795                         _ => panic!("Unexpected event"),
3796                 };
3797         } else {
3798                 assert_eq!(events_1.len(), 1);
3799                 match events_1[0] {
3800                         Event::PendingHTLCsForwardable { .. } => { },
3801                         _ => panic!("Unexpected event"),
3802                 };
3803         }
3804
3805         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3806         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3807         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3808
3809         nodes[1].node.process_pending_htlc_forwards();
3810
3811         let events_2 = nodes[1].node.get_and_clear_pending_events();
3812         assert_eq!(events_2.len(), 1);
3813         match events_2[0] {
3814                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3815                         assert_eq!(payment_hash_1, *payment_hash);
3816                         assert_eq!(amount_msat, 1_000_000);
3817                         assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3818                         assert_eq!(via_channel_id, Some(channel_id));
3819                         match &purpose {
3820                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3821                                         assert!(payment_preimage.is_none());
3822                                         assert_eq!(payment_secret_1, *payment_secret);
3823                                 },
3824                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3825                         }
3826                 },
3827                 _ => panic!("Unexpected event"),
3828         }
3829
3830         nodes[1].node.claim_funds(payment_preimage_1);
3831         check_added_monitors!(nodes[1], 1);
3832         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3833
3834         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3835         assert_eq!(events_3.len(), 1);
3836         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3837                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3838                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3839                         assert!(updates.update_add_htlcs.is_empty());
3840                         assert!(updates.update_fail_htlcs.is_empty());
3841                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3842                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3843                         assert!(updates.update_fee.is_none());
3844                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3845                 },
3846                 _ => panic!("Unexpected event"),
3847         };
3848
3849         if messages_delivered >= 1 {
3850                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3851
3852                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3853                 assert_eq!(events_4.len(), 1);
3854                 match events_4[0] {
3855                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3856                                 assert_eq!(payment_preimage_1, *payment_preimage);
3857                                 assert_eq!(payment_hash_1, *payment_hash);
3858                         },
3859                         _ => panic!("Unexpected event"),
3860                 }
3861
3862                 if messages_delivered >= 2 {
3863                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3864                         check_added_monitors!(nodes[0], 1);
3865                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3866
3867                         if messages_delivered >= 3 {
3868                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3869                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3870                                 check_added_monitors!(nodes[1], 1);
3871
3872                                 if messages_delivered >= 4 {
3873                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3874                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3875                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3876                                         check_added_monitors!(nodes[1], 1);
3877
3878                                         if messages_delivered >= 5 {
3879                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3880                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3881                                                 check_added_monitors!(nodes[0], 1);
3882                                         }
3883                                 }
3884                         }
3885                 }
3886         }
3887
3888         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3889         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3890         if messages_delivered < 2 {
3891                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3892                 if messages_delivered < 1 {
3893                         expect_payment_sent!(nodes[0], payment_preimage_1);
3894                 } else {
3895                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3896                 }
3897         } else if messages_delivered == 2 {
3898                 // nodes[0] still wants its RAA + commitment_signed
3899                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3900         } else if messages_delivered == 3 {
3901                 // nodes[0] still wants its commitment_signed
3902                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3903         } else if messages_delivered == 4 {
3904                 // nodes[1] still wants its final RAA
3905                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3906         } else if messages_delivered == 5 {
3907                 // Everything was delivered...
3908                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3909         }
3910
3911         if messages_delivered == 1 || messages_delivered == 2 {
3912                 expect_payment_path_successful!(nodes[0]);
3913         }
3914         if messages_delivered <= 5 {
3915                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3916                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3917         }
3918         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3919
3920         if messages_delivered > 2 {
3921                 expect_payment_path_successful!(nodes[0]);
3922         }
3923
3924         // Channel should still work fine...
3925         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3926         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3927         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3928 }
3929
3930 #[test]
3931 fn test_drop_messages_peer_disconnect_a() {
3932         do_test_drop_messages_peer_disconnect(0, true);
3933         do_test_drop_messages_peer_disconnect(0, false);
3934         do_test_drop_messages_peer_disconnect(1, false);
3935         do_test_drop_messages_peer_disconnect(2, false);
3936 }
3937
3938 #[test]
3939 fn test_drop_messages_peer_disconnect_b() {
3940         do_test_drop_messages_peer_disconnect(3, false);
3941         do_test_drop_messages_peer_disconnect(4, false);
3942         do_test_drop_messages_peer_disconnect(5, false);
3943         do_test_drop_messages_peer_disconnect(6, false);
3944 }
3945
3946 #[test]
3947 fn test_channel_ready_without_best_block_updated() {
3948         // Previously, if we were offline when a funding transaction was locked in, and then we came
3949         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3950         // generate a channel_ready until a later best_block_updated. This tests that we generate the
3951         // channel_ready immediately instead.
3952         let chanmon_cfgs = create_chanmon_cfgs(2);
3953         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3954         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3955         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3956         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3957
3958         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
3959
3960         let conf_height = nodes[0].best_block_info().1 + 1;
3961         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3962         let block_txn = [funding_tx];
3963         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3964         let conf_block_header = nodes[0].get_block_header(conf_height);
3965         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3966
3967         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
3968         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
3969         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3970 }
3971
3972 #[test]
3973 fn test_drop_messages_peer_disconnect_dual_htlc() {
3974         // Test that we can handle reconnecting when both sides of a channel have pending
3975         // commitment_updates when we disconnect.
3976         let chanmon_cfgs = create_chanmon_cfgs(2);
3977         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3978         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3979         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3980         create_announced_chan_between_nodes(&nodes, 0, 1);
3981
3982         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3983
3984         // Now try to send a second payment which will fail to send
3985         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3986         nodes[0].node.send_payment_with_route(&route, payment_hash_2,
3987                 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
3988         check_added_monitors!(nodes[0], 1);
3989
3990         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3991         assert_eq!(events_1.len(), 1);
3992         match events_1[0] {
3993                 MessageSendEvent::UpdateHTLCs { .. } => {},
3994                 _ => panic!("Unexpected event"),
3995         }
3996
3997         nodes[1].node.claim_funds(payment_preimage_1);
3998         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3999         check_added_monitors!(nodes[1], 1);
4000
4001         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4002         assert_eq!(events_2.len(), 1);
4003         match events_2[0] {
4004                 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 } } => {
4005                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4006                         assert!(update_add_htlcs.is_empty());
4007                         assert_eq!(update_fulfill_htlcs.len(), 1);
4008                         assert!(update_fail_htlcs.is_empty());
4009                         assert!(update_fail_malformed_htlcs.is_empty());
4010                         assert!(update_fee.is_none());
4011
4012                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4013                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4014                         assert_eq!(events_3.len(), 1);
4015                         match events_3[0] {
4016                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4017                                         assert_eq!(*payment_preimage, payment_preimage_1);
4018                                         assert_eq!(*payment_hash, payment_hash_1);
4019                                 },
4020                                 _ => panic!("Unexpected event"),
4021                         }
4022
4023                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4024                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4025                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4026                         check_added_monitors!(nodes[0], 1);
4027                 },
4028                 _ => panic!("Unexpected event"),
4029         }
4030
4031         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4032         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4033
4034         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();
4035         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4036         assert_eq!(reestablish_1.len(), 1);
4037         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();
4038         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4039         assert_eq!(reestablish_2.len(), 1);
4040
4041         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4042         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4043         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4044         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4045
4046         assert!(as_resp.0.is_none());
4047         assert!(bs_resp.0.is_none());
4048
4049         assert!(bs_resp.1.is_none());
4050         assert!(bs_resp.2.is_none());
4051
4052         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4053
4054         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4055         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4056         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4057         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4058         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4059         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4060         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4061         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4062         // No commitment_signed so get_event_msg's assert(len == 1) passes
4063         check_added_monitors!(nodes[1], 1);
4064
4065         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4066         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4067         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4068         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4069         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4070         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4071         assert!(bs_second_commitment_signed.update_fee.is_none());
4072         check_added_monitors!(nodes[1], 1);
4073
4074         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4075         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4076         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4077         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4078         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4079         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4080         assert!(as_commitment_signed.update_fee.is_none());
4081         check_added_monitors!(nodes[0], 1);
4082
4083         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4084         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4085         // No commitment_signed so get_event_msg's assert(len == 1) passes
4086         check_added_monitors!(nodes[0], 1);
4087
4088         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4089         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4090         // No commitment_signed so get_event_msg's assert(len == 1) passes
4091         check_added_monitors!(nodes[1], 1);
4092
4093         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4094         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4095         check_added_monitors!(nodes[1], 1);
4096
4097         expect_pending_htlcs_forwardable!(nodes[1]);
4098
4099         let events_5 = nodes[1].node.get_and_clear_pending_events();
4100         assert_eq!(events_5.len(), 1);
4101         match events_5[0] {
4102                 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4103                         assert_eq!(payment_hash_2, *payment_hash);
4104                         match &purpose {
4105                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4106                                         assert!(payment_preimage.is_none());
4107                                         assert_eq!(payment_secret_2, *payment_secret);
4108                                 },
4109                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4110                         }
4111                 },
4112                 _ => panic!("Unexpected event"),
4113         }
4114
4115         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4116         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4117         check_added_monitors!(nodes[0], 1);
4118
4119         expect_payment_path_successful!(nodes[0]);
4120         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4121 }
4122
4123 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4124         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4125         // to avoid our counterparty failing the channel.
4126         let chanmon_cfgs = create_chanmon_cfgs(2);
4127         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4128         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4129         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4130
4131         create_announced_chan_between_nodes(&nodes, 0, 1);
4132
4133         let our_payment_hash = if send_partial_mpp {
4134                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4135                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4136                 // indicates there are more HTLCs coming.
4137                 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.
4138                 let payment_id = PaymentId([42; 32]);
4139                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4140                         RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4141                 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4142                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4143                         &None, session_privs[0]).unwrap();
4144                 check_added_monitors!(nodes[0], 1);
4145                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4146                 assert_eq!(events.len(), 1);
4147                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4148                 // hop should *not* yet generate any PaymentClaimable event(s).
4149                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4150                 our_payment_hash
4151         } else {
4152                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4153         };
4154
4155         let mut block = Block {
4156                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
4157                 txdata: vec![],
4158         };
4159         connect_block(&nodes[0], &block);
4160         connect_block(&nodes[1], &block);
4161         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4162         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4163                 block.header.prev_blockhash = block.block_hash();
4164                 connect_block(&nodes[0], &block);
4165                 connect_block(&nodes[1], &block);
4166         }
4167
4168         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4169
4170         check_added_monitors!(nodes[1], 1);
4171         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4172         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4173         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4174         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4175         assert!(htlc_timeout_updates.update_fee.is_none());
4176
4177         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4178         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4179         // 100_000 msat as u64, followed by the height at which we failed back above
4180         let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4181         expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4182         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4183 }
4184
4185 #[test]
4186 fn test_htlc_timeout() {
4187         do_test_htlc_timeout(true);
4188         do_test_htlc_timeout(false);
4189 }
4190
4191 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4192         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4193         let chanmon_cfgs = create_chanmon_cfgs(3);
4194         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4195         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4196         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4197         create_announced_chan_between_nodes(&nodes, 0, 1);
4198         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4199
4200         // Make sure all nodes are at the same starting height
4201         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4202         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4203         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4204
4205         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4206         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4207         nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4208                 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4209         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4210         check_added_monitors!(nodes[1], 1);
4211
4212         // Now attempt to route a second payment, which should be placed in the holding cell
4213         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4214         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4215         sending_node.node.send_payment_with_route(&route, second_payment_hash,
4216                 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4217         if forwarded_htlc {
4218                 check_added_monitors!(nodes[0], 1);
4219                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4220                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4221                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4222                 expect_pending_htlcs_forwardable!(nodes[1]);
4223         }
4224         check_added_monitors!(nodes[1], 0);
4225
4226         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4227         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4228         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4229         connect_blocks(&nodes[1], 1);
4230
4231         if forwarded_htlc {
4232                 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 }]);
4233                 check_added_monitors!(nodes[1], 1);
4234                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4235                 assert_eq!(fail_commit.len(), 1);
4236                 match fail_commit[0] {
4237                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4238                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4239                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4240                         },
4241                         _ => unreachable!(),
4242                 }
4243                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4244         } else {
4245                 expect_payment_failed!(nodes[1], second_payment_hash, false);
4246         }
4247 }
4248
4249 #[test]
4250 fn test_holding_cell_htlc_add_timeouts() {
4251         do_test_holding_cell_htlc_add_timeouts(false);
4252         do_test_holding_cell_htlc_add_timeouts(true);
4253 }
4254
4255 macro_rules! check_spendable_outputs {
4256         ($node: expr, $keysinterface: expr) => {
4257                 {
4258                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4259                         let mut txn = Vec::new();
4260                         let mut all_outputs = Vec::new();
4261                         let secp_ctx = Secp256k1::new();
4262                         for event in events.drain(..) {
4263                                 match event {
4264                                         Event::SpendableOutputs { mut outputs } => {
4265                                                 for outp in outputs.drain(..) {
4266                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4267                                                         all_outputs.push(outp);
4268                                                 }
4269                                         },
4270                                         _ => panic!("Unexpected event"),
4271                                 };
4272                         }
4273                         if all_outputs.len() > 1 {
4274                                 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) {
4275                                         txn.push(tx);
4276                                 }
4277                         }
4278                         txn
4279                 }
4280         }
4281 }
4282
4283 #[test]
4284 fn test_claim_sizeable_push_msat() {
4285         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4286         let chanmon_cfgs = create_chanmon_cfgs(2);
4287         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4288         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4289         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4290
4291         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4292         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4293         check_closed_broadcast!(nodes[1], true);
4294         check_added_monitors!(nodes[1], 1);
4295         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4296         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4297         assert_eq!(node_txn.len(), 1);
4298         check_spends!(node_txn[0], chan.3);
4299         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
4300
4301         mine_transaction(&nodes[1], &node_txn[0]);
4302         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4303
4304         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4305         assert_eq!(spend_txn.len(), 1);
4306         assert_eq!(spend_txn[0].input.len(), 1);
4307         check_spends!(spend_txn[0], node_txn[0]);
4308         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4309 }
4310
4311 #[test]
4312 fn test_claim_on_remote_sizeable_push_msat() {
4313         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4314         // to_remote output is encumbered by a P2WPKH
4315         let chanmon_cfgs = create_chanmon_cfgs(2);
4316         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4317         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4318         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4319
4320         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4321         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4322         check_closed_broadcast!(nodes[0], true);
4323         check_added_monitors!(nodes[0], 1);
4324         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4325
4326         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4327         assert_eq!(node_txn.len(), 1);
4328         check_spends!(node_txn[0], chan.3);
4329         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
4330
4331         mine_transaction(&nodes[1], &node_txn[0]);
4332         check_closed_broadcast!(nodes[1], true);
4333         check_added_monitors!(nodes[1], 1);
4334         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4335         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4336
4337         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4338         assert_eq!(spend_txn.len(), 1);
4339         check_spends!(spend_txn[0], node_txn[0]);
4340 }
4341
4342 #[test]
4343 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4344         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4345         // to_remote output is encumbered by a P2WPKH
4346
4347         let chanmon_cfgs = create_chanmon_cfgs(2);
4348         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4349         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4350         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4351
4352         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4353         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4354         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4355         assert_eq!(revoked_local_txn[0].input.len(), 1);
4356         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4357
4358         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4359         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4360         check_closed_broadcast!(nodes[1], true);
4361         check_added_monitors!(nodes[1], 1);
4362         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4363
4364         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4365         mine_transaction(&nodes[1], &node_txn[0]);
4366         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4367
4368         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4369         assert_eq!(spend_txn.len(), 3);
4370         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4371         check_spends!(spend_txn[1], node_txn[0]);
4372         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4373 }
4374
4375 #[test]
4376 fn test_static_spendable_outputs_preimage_tx() {
4377         let chanmon_cfgs = create_chanmon_cfgs(2);
4378         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4379         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4380         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4381
4382         // Create some initial channels
4383         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4384
4385         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4386
4387         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4388         assert_eq!(commitment_tx[0].input.len(), 1);
4389         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4390
4391         // Settle A's commitment tx on B's chain
4392         nodes[1].node.claim_funds(payment_preimage);
4393         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4394         check_added_monitors!(nodes[1], 1);
4395         mine_transaction(&nodes[1], &commitment_tx[0]);
4396         check_added_monitors!(nodes[1], 1);
4397         let events = nodes[1].node.get_and_clear_pending_msg_events();
4398         match events[0] {
4399                 MessageSendEvent::UpdateHTLCs { .. } => {},
4400                 _ => panic!("Unexpected event"),
4401         }
4402         match events[1] {
4403                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4404                 _ => panic!("Unexepected event"),
4405         }
4406
4407         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4408         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4409         assert_eq!(node_txn.len(), 1);
4410         check_spends!(node_txn[0], commitment_tx[0]);
4411         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4412
4413         mine_transaction(&nodes[1], &node_txn[0]);
4414         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4415         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4416
4417         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4418         assert_eq!(spend_txn.len(), 1);
4419         check_spends!(spend_txn[0], node_txn[0]);
4420 }
4421
4422 #[test]
4423 fn test_static_spendable_outputs_timeout_tx() {
4424         let chanmon_cfgs = create_chanmon_cfgs(2);
4425         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4426         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4427         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4428
4429         // Create some initial channels
4430         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4431
4432         // Rebalance the network a bit by relaying one payment through all the channels ...
4433         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4434
4435         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4436
4437         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4438         assert_eq!(commitment_tx[0].input.len(), 1);
4439         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4440
4441         // Settle A's commitment tx on B' chain
4442         mine_transaction(&nodes[1], &commitment_tx[0]);
4443         check_added_monitors!(nodes[1], 1);
4444         let events = nodes[1].node.get_and_clear_pending_msg_events();
4445         match events[0] {
4446                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4447                 _ => panic!("Unexpected event"),
4448         }
4449         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4450
4451         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4452         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4453         assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4454         check_spends!(node_txn[0],  commitment_tx[0].clone());
4455         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4456
4457         mine_transaction(&nodes[1], &node_txn[0]);
4458         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4459         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4460         expect_payment_failed!(nodes[1], our_payment_hash, false);
4461
4462         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4463         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4464         check_spends!(spend_txn[0], commitment_tx[0]);
4465         check_spends!(spend_txn[1], node_txn[0]);
4466         check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4467 }
4468
4469 #[test]
4470 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4471         let chanmon_cfgs = create_chanmon_cfgs(2);
4472         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4473         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4474         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4475
4476         // Create some initial channels
4477         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4478
4479         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4480         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4481         assert_eq!(revoked_local_txn[0].input.len(), 1);
4482         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4483
4484         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4485
4486         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4487         check_closed_broadcast!(nodes[1], true);
4488         check_added_monitors!(nodes[1], 1);
4489         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4490
4491         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4492         assert_eq!(node_txn.len(), 1);
4493         assert_eq!(node_txn[0].input.len(), 2);
4494         check_spends!(node_txn[0], revoked_local_txn[0]);
4495
4496         mine_transaction(&nodes[1], &node_txn[0]);
4497         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4498
4499         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4500         assert_eq!(spend_txn.len(), 1);
4501         check_spends!(spend_txn[0], node_txn[0]);
4502 }
4503
4504 #[test]
4505 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4506         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4507         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4508         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4509         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4510         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4511
4512         // Create some initial channels
4513         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4514
4515         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4516         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4517         assert_eq!(revoked_local_txn[0].input.len(), 1);
4518         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4519
4520         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4521
4522         // A will generate HTLC-Timeout from revoked commitment tx
4523         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4524         check_closed_broadcast!(nodes[0], true);
4525         check_added_monitors!(nodes[0], 1);
4526         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4527         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4528
4529         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4530         assert_eq!(revoked_htlc_txn.len(), 1);
4531         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4532         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4533         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4534         assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4535
4536         // B will generate justice tx from A's revoked commitment/HTLC tx
4537         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4538         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4539         check_closed_broadcast!(nodes[1], true);
4540         check_added_monitors!(nodes[1], 1);
4541         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4542
4543         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4544         assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4545         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4546         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4547         // transactions next...
4548         assert_eq!(node_txn[0].input.len(), 3);
4549         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4550
4551         assert_eq!(node_txn[1].input.len(), 2);
4552         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4553         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4554                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4555         } else {
4556                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4557                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4558         }
4559
4560         mine_transaction(&nodes[1], &node_txn[1]);
4561         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4562
4563         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4564         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4565         assert_eq!(spend_txn.len(), 1);
4566         assert_eq!(spend_txn[0].input.len(), 1);
4567         check_spends!(spend_txn[0], node_txn[1]);
4568 }
4569
4570 #[test]
4571 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4572         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4573         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4574         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4575         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4576         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4577
4578         // Create some initial channels
4579         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4580
4581         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4582         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4583         assert_eq!(revoked_local_txn[0].input.len(), 1);
4584         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4585
4586         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4587         assert_eq!(revoked_local_txn[0].output.len(), 2);
4588
4589         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4590
4591         // B will generate HTLC-Success from revoked commitment tx
4592         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4593         check_closed_broadcast!(nodes[1], true);
4594         check_added_monitors!(nodes[1], 1);
4595         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4596         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4597
4598         assert_eq!(revoked_htlc_txn.len(), 1);
4599         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4600         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4601         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4602
4603         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4604         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4605         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4606
4607         // A will generate justice tx from B's revoked commitment/HTLC tx
4608         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4609         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4610         check_closed_broadcast!(nodes[0], true);
4611         check_added_monitors!(nodes[0], 1);
4612         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4613
4614         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4615         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4616
4617         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4618         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4619         // transactions next...
4620         assert_eq!(node_txn[0].input.len(), 2);
4621         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4622         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4623                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4624         } else {
4625                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4626                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4627         }
4628
4629         assert_eq!(node_txn[1].input.len(), 1);
4630         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4631
4632         mine_transaction(&nodes[0], &node_txn[1]);
4633         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4634
4635         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4636         // didn't try to generate any new transactions.
4637
4638         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4639         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4640         assert_eq!(spend_txn.len(), 3);
4641         assert_eq!(spend_txn[0].input.len(), 1);
4642         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4643         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4644         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4645         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4646 }
4647
4648 #[test]
4649 fn test_onchain_to_onchain_claim() {
4650         // Test that in case of channel closure, we detect the state of output and claim HTLC
4651         // on downstream peer's remote commitment tx.
4652         // First, have C claim an HTLC against its own latest commitment transaction.
4653         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4654         // channel.
4655         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4656         // gets broadcast.
4657
4658         let chanmon_cfgs = create_chanmon_cfgs(3);
4659         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4660         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4661         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4662
4663         // Create some initial channels
4664         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4665         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4666
4667         // Ensure all nodes are at the same height
4668         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4669         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4670         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4671         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4672
4673         // Rebalance the network a bit by relaying one payment through all the channels ...
4674         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4675         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4676
4677         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4678         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4679         check_spends!(commitment_tx[0], chan_2.3);
4680         nodes[2].node.claim_funds(payment_preimage);
4681         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4682         check_added_monitors!(nodes[2], 1);
4683         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4684         assert!(updates.update_add_htlcs.is_empty());
4685         assert!(updates.update_fail_htlcs.is_empty());
4686         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4687         assert!(updates.update_fail_malformed_htlcs.is_empty());
4688
4689         mine_transaction(&nodes[2], &commitment_tx[0]);
4690         check_closed_broadcast!(nodes[2], true);
4691         check_added_monitors!(nodes[2], 1);
4692         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4693
4694         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4695         assert_eq!(c_txn.len(), 1);
4696         check_spends!(c_txn[0], commitment_tx[0]);
4697         assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4698         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4699         assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4700
4701         // 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
4702         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
4703         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone(), c_txn[0].clone()]});
4704         check_added_monitors!(nodes[1], 1);
4705         let events = nodes[1].node.get_and_clear_pending_events();
4706         assert_eq!(events.len(), 2);
4707         match events[0] {
4708                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4709                 _ => panic!("Unexpected event"),
4710         }
4711         match events[1] {
4712                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4713                         assert_eq!(fee_earned_msat, Some(1000));
4714                         assert_eq!(prev_channel_id, Some(chan_1.2));
4715                         assert_eq!(claim_from_onchain_tx, true);
4716                         assert_eq!(next_channel_id, Some(chan_2.2));
4717                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4718                 },
4719                 _ => panic!("Unexpected event"),
4720         }
4721         check_added_monitors!(nodes[1], 1);
4722         let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4723         assert_eq!(msg_events.len(), 3);
4724         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4725         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4726
4727         match nodes_2_event {
4728                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4729                 _ => panic!("Unexpected event"),
4730         }
4731
4732         match nodes_0_event {
4733                 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, .. } } => {
4734                         assert!(update_add_htlcs.is_empty());
4735                         assert!(update_fail_htlcs.is_empty());
4736                         assert_eq!(update_fulfill_htlcs.len(), 1);
4737                         assert!(update_fail_malformed_htlcs.is_empty());
4738                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4739                 },
4740                 _ => panic!("Unexpected event"),
4741         };
4742
4743         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4744         match msg_events[0] {
4745                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4746                 _ => panic!("Unexpected event"),
4747         }
4748
4749         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4750         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4751         mine_transaction(&nodes[1], &commitment_tx[0]);
4752         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4753         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4754         // ChannelMonitor: HTLC-Success tx
4755         assert_eq!(b_txn.len(), 1);
4756         check_spends!(b_txn[0], commitment_tx[0]);
4757         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4758         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4759         assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1); // Success tx
4760
4761         check_closed_broadcast!(nodes[1], true);
4762         check_added_monitors!(nodes[1], 1);
4763 }
4764
4765 #[test]
4766 fn test_duplicate_payment_hash_one_failure_one_success() {
4767         // Topology : A --> B --> C --> D
4768         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4769         // Note that because C will refuse to generate two payment secrets for the same payment hash,
4770         // we forward one of the payments onwards to D.
4771         let chanmon_cfgs = create_chanmon_cfgs(4);
4772         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4773         // When this test was written, the default base fee floated based on the HTLC count.
4774         // It is now fixed, so we simply set the fee to the expected value here.
4775         let mut config = test_default_channel_config();
4776         config.channel_config.forwarding_fee_base_msat = 196;
4777         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4778                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4779         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4780
4781         create_announced_chan_between_nodes(&nodes, 0, 1);
4782         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4783         create_announced_chan_between_nodes(&nodes, 2, 3);
4784
4785         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4786         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4787         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4788         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4789         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4790
4791         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4792
4793         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4794         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4795         // script push size limit so that the below script length checks match
4796         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4797         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4798                 .with_features(nodes[3].node.invoice_features());
4799         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000, TEST_FINAL_CLTV - 40);
4800         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4801
4802         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4803         assert_eq!(commitment_txn[0].input.len(), 1);
4804         check_spends!(commitment_txn[0], chan_2.3);
4805
4806         mine_transaction(&nodes[1], &commitment_txn[0]);
4807         check_closed_broadcast!(nodes[1], true);
4808         check_added_monitors!(nodes[1], 1);
4809         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4810         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
4811
4812         let htlc_timeout_tx;
4813         { // Extract one of the two HTLC-Timeout transaction
4814                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4815                 // ChannelMonitor: timeout tx * 2-or-3
4816                 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4817
4818                 check_spends!(node_txn[0], commitment_txn[0]);
4819                 assert_eq!(node_txn[0].input.len(), 1);
4820                 assert_eq!(node_txn[0].output.len(), 1);
4821
4822                 if node_txn.len() > 2 {
4823                         check_spends!(node_txn[1], commitment_txn[0]);
4824                         assert_eq!(node_txn[1].input.len(), 1);
4825                         assert_eq!(node_txn[1].output.len(), 1);
4826                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4827
4828                         check_spends!(node_txn[2], commitment_txn[0]);
4829                         assert_eq!(node_txn[2].input.len(), 1);
4830                         assert_eq!(node_txn[2].output.len(), 1);
4831                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4832                 } else {
4833                         check_spends!(node_txn[1], commitment_txn[0]);
4834                         assert_eq!(node_txn[1].input.len(), 1);
4835                         assert_eq!(node_txn[1].output.len(), 1);
4836                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4837                 }
4838
4839                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4840                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4841                 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
4842                 // (with value 900 sats) will be claimed in the below `claim_funds` call.
4843                 if node_txn.len() > 2 {
4844                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4845                         htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
4846                 } else {
4847                         htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
4848                 }
4849         }
4850
4851         nodes[2].node.claim_funds(our_payment_preimage);
4852         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4853
4854         mine_transaction(&nodes[2], &commitment_txn[0]);
4855         check_added_monitors!(nodes[2], 2);
4856         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4857         let events = nodes[2].node.get_and_clear_pending_msg_events();
4858         match events[0] {
4859                 MessageSendEvent::UpdateHTLCs { .. } => {},
4860                 _ => panic!("Unexpected event"),
4861         }
4862         match events[1] {
4863                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4864                 _ => panic!("Unexepected event"),
4865         }
4866         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4867         assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4868         check_spends!(htlc_success_txn[0], commitment_txn[0]);
4869         check_spends!(htlc_success_txn[1], commitment_txn[0]);
4870         assert_eq!(htlc_success_txn[0].input.len(), 1);
4871         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4872         assert_eq!(htlc_success_txn[1].input.len(), 1);
4873         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4874         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4875         assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4876
4877         mine_transaction(&nodes[1], &htlc_timeout_tx);
4878         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4879         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 }]);
4880         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4881         assert!(htlc_updates.update_add_htlcs.is_empty());
4882         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4883         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4884         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4885         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4886         check_added_monitors!(nodes[1], 1);
4887
4888         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4889         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4890         {
4891                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4892         }
4893         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
4894
4895         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4896         mine_transaction(&nodes[1], &htlc_success_txn[1]);
4897         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
4898         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4899         assert!(updates.update_add_htlcs.is_empty());
4900         assert!(updates.update_fail_htlcs.is_empty());
4901         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4902         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
4903         assert!(updates.update_fail_malformed_htlcs.is_empty());
4904         check_added_monitors!(nodes[1], 1);
4905
4906         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4907         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4908         expect_payment_sent(&nodes[0], our_payment_preimage, None, true);
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); // 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); // 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].hops[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].hops[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].hops[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].hops[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].hops.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].hops[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..50 {
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 = (50) 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); // 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, 11);
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         for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
7112                 nodes[0].node.timer_tick_occurred();
7113         }
7114         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7115         assert_eq!(msg_events.len(), 3);
7116         let mut chans_disabled = HashMap::new();
7117         for e in msg_events {
7118                 match e {
7119                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7120                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7121                                 // Check that each channel gets updated exactly once
7122                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7123                                         panic!("Generated ChannelUpdate for wrong chan!");
7124                                 }
7125                         },
7126                         _ => panic!("Unexpected event"),
7127                 }
7128         }
7129         // Reconnect peers
7130         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();
7131         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7132         assert_eq!(reestablish_1.len(), 3);
7133         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();
7134         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7135         assert_eq!(reestablish_2.len(), 3);
7136
7137         // Reestablish chan_1
7138         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7139         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7140         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7141         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7142         // Reestablish chan_2
7143         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7144         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7145         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7146         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7147         // Reestablish chan_3
7148         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7149         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7150         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7151         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7152
7153         for _ in 0..ENABLE_GOSSIP_TICKS {
7154                 nodes[0].node.timer_tick_occurred();
7155         }
7156         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7157         nodes[0].node.timer_tick_occurred();
7158         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7159         assert_eq!(msg_events.len(), 3);
7160         for e in msg_events {
7161                 match e {
7162                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7163                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7164                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7165                                         // Each update should have a higher timestamp than the previous one, replacing
7166                                         // the old one.
7167                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7168                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7169                                 }
7170                         },
7171                         _ => panic!("Unexpected event"),
7172                 }
7173         }
7174         // Check that each channel gets updated exactly once
7175         assert!(chans_disabled.is_empty());
7176 }
7177
7178 #[test]
7179 fn test_bump_penalty_txn_on_revoked_commitment() {
7180         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7181         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7182
7183         let chanmon_cfgs = create_chanmon_cfgs(2);
7184         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7185         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7186         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7187
7188         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7189
7190         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7191         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7192                 .with_features(nodes[0].node.invoice_features());
7193         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7194         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7195
7196         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7197         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7198         assert_eq!(revoked_txn[0].output.len(), 4);
7199         assert_eq!(revoked_txn[0].input.len(), 1);
7200         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7201         let revoked_txid = revoked_txn[0].txid();
7202
7203         let mut penalty_sum = 0;
7204         for outp in revoked_txn[0].output.iter() {
7205                 if outp.script_pubkey.is_v0_p2wsh() {
7206                         penalty_sum += outp.value;
7207                 }
7208         }
7209
7210         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7211         let header_114 = connect_blocks(&nodes[1], 14);
7212
7213         // Actually revoke tx by claiming a HTLC
7214         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7215         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7216         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7217         check_added_monitors!(nodes[1], 1);
7218
7219         // One or more justice tx should have been broadcast, check it
7220         let penalty_1;
7221         let feerate_1;
7222         {
7223                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7224                 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7225                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7226                 assert_eq!(node_txn[0].output.len(), 1);
7227                 check_spends!(node_txn[0], revoked_txn[0]);
7228                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7229                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7230                 penalty_1 = node_txn[0].txid();
7231                 node_txn.clear();
7232         };
7233
7234         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7235         connect_blocks(&nodes[1], 15);
7236         let mut penalty_2 = penalty_1;
7237         let mut feerate_2 = 0;
7238         {
7239                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7240                 assert_eq!(node_txn.len(), 1);
7241                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7242                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7243                         assert_eq!(node_txn[0].output.len(), 1);
7244                         check_spends!(node_txn[0], revoked_txn[0]);
7245                         penalty_2 = node_txn[0].txid();
7246                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7247                         assert_ne!(penalty_2, penalty_1);
7248                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7249                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7250                         // Verify 25% bump heuristic
7251                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7252                         node_txn.clear();
7253                 }
7254         }
7255         assert_ne!(feerate_2, 0);
7256
7257         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7258         connect_blocks(&nodes[1], 1);
7259         let penalty_3;
7260         let mut feerate_3 = 0;
7261         {
7262                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7263                 assert_eq!(node_txn.len(), 1);
7264                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7265                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7266                         assert_eq!(node_txn[0].output.len(), 1);
7267                         check_spends!(node_txn[0], revoked_txn[0]);
7268                         penalty_3 = node_txn[0].txid();
7269                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7270                         assert_ne!(penalty_3, penalty_2);
7271                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7272                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7273                         // Verify 25% bump heuristic
7274                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7275                         node_txn.clear();
7276                 }
7277         }
7278         assert_ne!(feerate_3, 0);
7279
7280         nodes[1].node.get_and_clear_pending_events();
7281         nodes[1].node.get_and_clear_pending_msg_events();
7282 }
7283
7284 #[test]
7285 fn test_bump_penalty_txn_on_revoked_htlcs() {
7286         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7287         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7288
7289         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7290         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7291         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7292         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7293         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7294
7295         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7296         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7297         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_features(nodes[1].node.invoice_features());
7298         let scorer = test_utils::TestScorer::new();
7299         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7300         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7301                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7302         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7303         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_features(nodes[0].node.invoice_features());
7304         let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7305                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7306         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7307
7308         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7309         assert_eq!(revoked_local_txn[0].input.len(), 1);
7310         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7311
7312         // Revoke local commitment tx
7313         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7314
7315         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7316         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7317         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7318         check_closed_broadcast!(nodes[1], true);
7319         check_added_monitors!(nodes[1], 1);
7320         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7321         connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7322
7323         let revoked_htlc_txn = {
7324                 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7325                 assert_eq!(txn.len(), 2);
7326
7327                 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7328                 assert_eq!(txn[0].input.len(), 1);
7329                 check_spends!(txn[0], revoked_local_txn[0]);
7330
7331                 assert_eq!(txn[1].input.len(), 1);
7332                 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7333                 assert_eq!(txn[1].output.len(), 1);
7334                 check_spends!(txn[1], revoked_local_txn[0]);
7335
7336                 txn
7337         };
7338
7339         // Broadcast set of revoked txn on A
7340         let hash_128 = connect_blocks(&nodes[0], 40);
7341         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7342         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7343         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7344         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] });
7345         let events = nodes[0].node.get_and_clear_pending_events();
7346         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7347         match events.last().unwrap() {
7348                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7349                 _ => panic!("Unexpected event"),
7350         }
7351         let first;
7352         let feerate_1;
7353         let penalty_txn;
7354         {
7355                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7356                 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7357                 // Verify claim tx are spending revoked HTLC txn
7358
7359                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7360                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7361                 // which are included in the same block (they are broadcasted because we scan the
7362                 // transactions linearly and generate claims as we go, they likely should be removed in the
7363                 // future).
7364                 assert_eq!(node_txn[0].input.len(), 1);
7365                 check_spends!(node_txn[0], revoked_local_txn[0]);
7366                 assert_eq!(node_txn[1].input.len(), 1);
7367                 check_spends!(node_txn[1], revoked_local_txn[0]);
7368                 assert_eq!(node_txn[2].input.len(), 1);
7369                 check_spends!(node_txn[2], revoked_local_txn[0]);
7370
7371                 // Each of the three justice transactions claim a separate (single) output of the three
7372                 // available, which we check here:
7373                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7374                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7375                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7376
7377                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7378                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7379
7380                 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7381                 // output, checked above).
7382                 assert_eq!(node_txn[3].input.len(), 2);
7383                 assert_eq!(node_txn[3].output.len(), 1);
7384                 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7385
7386                 first = node_txn[3].txid();
7387                 // Store both feerates for later comparison
7388                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7389                 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7390                 penalty_txn = vec![node_txn[2].clone()];
7391                 node_txn.clear();
7392         }
7393
7394         // Connect one more block to see if bumped penalty are issued for HTLC txn
7395         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7396         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7397         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7398         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7399
7400         // Few more blocks to confirm penalty txn
7401         connect_blocks(&nodes[0], 4);
7402         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7403         let header_144 = connect_blocks(&nodes[0], 9);
7404         let node_txn = {
7405                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7406                 assert_eq!(node_txn.len(), 1);
7407
7408                 assert_eq!(node_txn[0].input.len(), 2);
7409                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7410                 // Verify bumped tx is different and 25% bump heuristic
7411                 assert_ne!(first, node_txn[0].txid());
7412                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7413                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7414                 assert!(feerate_2 * 100 > feerate_1 * 125);
7415                 let txn = vec![node_txn[0].clone()];
7416                 node_txn.clear();
7417                 txn
7418         };
7419         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7420         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7421         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7422         connect_blocks(&nodes[0], 20);
7423         {
7424                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7425                 // We verify than no new transaction has been broadcast because previously
7426                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7427                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7428                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7429                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7430                 // up bumped justice generation.
7431                 assert_eq!(node_txn.len(), 0);
7432                 node_txn.clear();
7433         }
7434         check_closed_broadcast!(nodes[0], true);
7435         check_added_monitors!(nodes[0], 1);
7436 }
7437
7438 #[test]
7439 fn test_bump_penalty_txn_on_remote_commitment() {
7440         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7441         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7442
7443         // Create 2 HTLCs
7444         // Provide preimage for one
7445         // Check aggregation
7446
7447         let chanmon_cfgs = create_chanmon_cfgs(2);
7448         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7449         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7450         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7451
7452         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7453         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7454         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7455
7456         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7457         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7458         assert_eq!(remote_txn[0].output.len(), 4);
7459         assert_eq!(remote_txn[0].input.len(), 1);
7460         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7461
7462         // Claim a HTLC without revocation (provide B monitor with preimage)
7463         nodes[1].node.claim_funds(payment_preimage);
7464         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7465         mine_transaction(&nodes[1], &remote_txn[0]);
7466         check_added_monitors!(nodes[1], 2);
7467         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7468
7469         // One or more claim tx should have been broadcast, check it
7470         let timeout;
7471         let preimage;
7472         let preimage_bump;
7473         let feerate_timeout;
7474         let feerate_preimage;
7475         {
7476                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7477                 // 3 transactions including:
7478                 //   preimage and timeout sweeps from remote commitment + preimage sweep bump
7479                 assert_eq!(node_txn.len(), 3);
7480                 assert_eq!(node_txn[0].input.len(), 1);
7481                 assert_eq!(node_txn[1].input.len(), 1);
7482                 assert_eq!(node_txn[2].input.len(), 1);
7483                 check_spends!(node_txn[0], remote_txn[0]);
7484                 check_spends!(node_txn[1], remote_txn[0]);
7485                 check_spends!(node_txn[2], remote_txn[0]);
7486
7487                 preimage = node_txn[0].txid();
7488                 let index = node_txn[0].input[0].previous_output.vout;
7489                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7490                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7491
7492                 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7493                         (node_txn[2].clone(), node_txn[1].clone())
7494                 } else {
7495                         (node_txn[1].clone(), node_txn[2].clone())
7496                 };
7497
7498                 preimage_bump = preimage_bump_tx;
7499                 check_spends!(preimage_bump, remote_txn[0]);
7500                 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7501
7502                 timeout = timeout_tx.txid();
7503                 let index = timeout_tx.input[0].previous_output.vout;
7504                 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7505                 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7506
7507                 node_txn.clear();
7508         };
7509         assert_ne!(feerate_timeout, 0);
7510         assert_ne!(feerate_preimage, 0);
7511
7512         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7513         connect_blocks(&nodes[1], 1);
7514         {
7515                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7516                 assert_eq!(node_txn.len(), 1);
7517                 assert_eq!(node_txn[0].input.len(), 1);
7518                 assert_eq!(preimage_bump.input.len(), 1);
7519                 check_spends!(node_txn[0], remote_txn[0]);
7520                 check_spends!(preimage_bump, remote_txn[0]);
7521
7522                 let index = preimage_bump.input[0].previous_output.vout;
7523                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7524                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7525                 assert!(new_feerate * 100 > feerate_timeout * 125);
7526                 assert_ne!(timeout, preimage_bump.txid());
7527
7528                 let index = node_txn[0].input[0].previous_output.vout;
7529                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7530                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7531                 assert!(new_feerate * 100 > feerate_preimage * 125);
7532                 assert_ne!(preimage, node_txn[0].txid());
7533
7534                 node_txn.clear();
7535         }
7536
7537         nodes[1].node.get_and_clear_pending_events();
7538         nodes[1].node.get_and_clear_pending_msg_events();
7539 }
7540
7541 #[test]
7542 fn test_counterparty_raa_skip_no_crash() {
7543         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7544         // commitment transaction, we would have happily carried on and provided them the next
7545         // commitment transaction based on one RAA forward. This would probably eventually have led to
7546         // channel closure, but it would not have resulted in funds loss. Still, our
7547         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7548         // check simply that the channel is closed in response to such an RAA, but don't check whether
7549         // we decide to punish our counterparty for revoking their funds (as we don't currently
7550         // implement that).
7551         let chanmon_cfgs = create_chanmon_cfgs(2);
7552         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7553         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7554         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7555         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7556
7557         let per_commitment_secret;
7558         let next_per_commitment_point;
7559         {
7560                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7561                 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7562                 let keys = guard.channel_by_id.get_mut(&channel_id).unwrap().get_signer();
7563
7564                 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7565
7566                 // Make signer believe we got a counterparty signature, so that it allows the revocation
7567                 keys.get_enforcement_state().last_holder_commitment -= 1;
7568                 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7569
7570                 // Must revoke without gaps
7571                 keys.get_enforcement_state().last_holder_commitment -= 1;
7572                 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7573
7574                 keys.get_enforcement_state().last_holder_commitment -= 1;
7575                 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7576                         &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7577         }
7578
7579         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7580                 &msgs::RevokeAndACK {
7581                         channel_id,
7582                         per_commitment_secret,
7583                         next_per_commitment_point,
7584                         #[cfg(taproot)]
7585                         next_local_nonce: None,
7586                 });
7587         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7588         check_added_monitors!(nodes[1], 1);
7589         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7590 }
7591
7592 #[test]
7593 fn test_bump_txn_sanitize_tracking_maps() {
7594         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7595         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7596
7597         let chanmon_cfgs = create_chanmon_cfgs(2);
7598         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7599         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7600         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7601
7602         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7603         // Lock HTLC in both directions
7604         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7605         let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7606
7607         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7608         assert_eq!(revoked_local_txn[0].input.len(), 1);
7609         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7610
7611         // Revoke local commitment tx
7612         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7613
7614         // Broadcast set of revoked txn on A
7615         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7616         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7617         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7618
7619         mine_transaction(&nodes[0], &revoked_local_txn[0]);
7620         check_closed_broadcast!(nodes[0], true);
7621         check_added_monitors!(nodes[0], 1);
7622         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7623         let penalty_txn = {
7624                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7625                 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7626                 check_spends!(node_txn[0], revoked_local_txn[0]);
7627                 check_spends!(node_txn[1], revoked_local_txn[0]);
7628                 check_spends!(node_txn[2], revoked_local_txn[0]);
7629                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7630                 node_txn.clear();
7631                 penalty_txn
7632         };
7633         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7634         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7635         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7636         {
7637                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7638                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7639                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7640         }
7641 }
7642
7643 #[test]
7644 fn test_pending_claimed_htlc_no_balance_underflow() {
7645         // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
7646         // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
7647         let chanmon_cfgs = create_chanmon_cfgs(2);
7648         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7649         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7650         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7651         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
7652
7653         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
7654         nodes[1].node.claim_funds(payment_preimage);
7655         expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
7656         check_added_monitors!(nodes[1], 1);
7657         let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7658
7659         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
7660         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
7661         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
7662         check_added_monitors!(nodes[0], 1);
7663         let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7664
7665         // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
7666         // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
7667         // can get our balance.
7668
7669         // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
7670         // the public key of the only hop. This works around ChannelDetails not showing the
7671         // almost-claimed HTLC as available balance.
7672         let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
7673         route.payment_params = None; // This is all wrong, but unnecessary
7674         route.paths[0].hops[0].pubkey = nodes[0].node.get_our_node_id();
7675         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
7676         nodes[1].node.send_payment_with_route(&route, payment_hash_2,
7677                 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
7678
7679         assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
7680 }
7681
7682 #[test]
7683 fn test_channel_conf_timeout() {
7684         // Tests that, for inbound channels, we give up on them if the funding transaction does not
7685         // confirm within 2016 blocks, as recommended by BOLT 2.
7686         let chanmon_cfgs = create_chanmon_cfgs(2);
7687         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7688         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7689         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7690
7691         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7692
7693         // The outbound node should wait forever for confirmation:
7694         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7695         // copied here instead of directly referencing the constant.
7696         connect_blocks(&nodes[0], 2016);
7697         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7698
7699         // The inbound node should fail the channel after exactly 2016 blocks
7700         connect_blocks(&nodes[1], 2015);
7701         check_added_monitors!(nodes[1], 0);
7702         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7703
7704         connect_blocks(&nodes[1], 1);
7705         check_added_monitors!(nodes[1], 1);
7706         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
7707         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7708         assert_eq!(close_ev.len(), 1);
7709         match close_ev[0] {
7710                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7711                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7712                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7713                 },
7714                 _ => panic!("Unexpected event"),
7715         }
7716 }
7717
7718 #[test]
7719 fn test_override_channel_config() {
7720         let chanmon_cfgs = create_chanmon_cfgs(2);
7721         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7722         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7723         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7724
7725         // Node0 initiates a channel to node1 using the override config.
7726         let mut override_config = UserConfig::default();
7727         override_config.channel_handshake_config.our_to_self_delay = 200;
7728
7729         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7730
7731         // Assert the channel created by node0 is using the override config.
7732         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7733         assert_eq!(res.channel_flags, 0);
7734         assert_eq!(res.to_self_delay, 200);
7735 }
7736
7737 #[test]
7738 fn test_override_0msat_htlc_minimum() {
7739         let mut zero_config = UserConfig::default();
7740         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7741         let chanmon_cfgs = create_chanmon_cfgs(2);
7742         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7743         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7744         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7745
7746         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7747         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7748         assert_eq!(res.htlc_minimum_msat, 1);
7749
7750         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7751         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7752         assert_eq!(res.htlc_minimum_msat, 1);
7753 }
7754
7755 #[test]
7756 fn test_channel_update_has_correct_htlc_maximum_msat() {
7757         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7758         // Bolt 7 specifies that if present `htlc_maximum_msat`:
7759         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7760         // 90% of the `channel_value`.
7761         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7762
7763         let mut config_30_percent = UserConfig::default();
7764         config_30_percent.channel_handshake_config.announced_channel = true;
7765         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7766         let mut config_50_percent = UserConfig::default();
7767         config_50_percent.channel_handshake_config.announced_channel = true;
7768         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7769         let mut config_95_percent = UserConfig::default();
7770         config_95_percent.channel_handshake_config.announced_channel = true;
7771         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7772         let mut config_100_percent = UserConfig::default();
7773         config_100_percent.channel_handshake_config.announced_channel = true;
7774         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7775
7776         let chanmon_cfgs = create_chanmon_cfgs(4);
7777         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7778         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)]);
7779         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7780
7781         let channel_value_satoshis = 100000;
7782         let channel_value_msat = channel_value_satoshis * 1000;
7783         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7784         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7785         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7786
7787         let (node_0_chan_update, node_1_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7788         let (node_2_chan_update, node_3_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7789
7790         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7791         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7792         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7793         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7794         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7795         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7796
7797         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7798         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7799         // `channel_value`.
7800         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7801         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7802         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7803         // `channel_value`.
7804         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7805 }
7806
7807 #[test]
7808 fn test_manually_accept_inbound_channel_request() {
7809         let mut manually_accept_conf = UserConfig::default();
7810         manually_accept_conf.manually_accept_inbound_channels = true;
7811         let chanmon_cfgs = create_chanmon_cfgs(2);
7812         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7813         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7814         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7815
7816         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7817         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7818
7819         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7820
7821         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7822         // accepting the inbound channel request.
7823         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7824
7825         let events = nodes[1].node.get_and_clear_pending_events();
7826         match events[0] {
7827                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7828                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7829                 }
7830                 _ => panic!("Unexpected event"),
7831         }
7832
7833         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7834         assert_eq!(accept_msg_ev.len(), 1);
7835
7836         match accept_msg_ev[0] {
7837                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7838                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7839                 }
7840                 _ => panic!("Unexpected event"),
7841         }
7842
7843         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7844
7845         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7846         assert_eq!(close_msg_ev.len(), 1);
7847
7848         let events = nodes[1].node.get_and_clear_pending_events();
7849         match events[0] {
7850                 Event::ChannelClosed { user_channel_id, .. } => {
7851                         assert_eq!(user_channel_id, 23);
7852                 }
7853                 _ => panic!("Unexpected event"),
7854         }
7855 }
7856
7857 #[test]
7858 fn test_manually_reject_inbound_channel_request() {
7859         let mut manually_accept_conf = UserConfig::default();
7860         manually_accept_conf.manually_accept_inbound_channels = true;
7861         let chanmon_cfgs = create_chanmon_cfgs(2);
7862         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7863         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7864         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7865
7866         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7867         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7868
7869         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7870
7871         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7872         // rejecting the inbound channel request.
7873         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7874
7875         let events = nodes[1].node.get_and_clear_pending_events();
7876         match events[0] {
7877                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7878                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7879                 }
7880                 _ => panic!("Unexpected event"),
7881         }
7882
7883         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7884         assert_eq!(close_msg_ev.len(), 1);
7885
7886         match close_msg_ev[0] {
7887                 MessageSendEvent::HandleError { ref node_id, .. } => {
7888                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7889                 }
7890                 _ => panic!("Unexpected event"),
7891         }
7892         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
7893 }
7894
7895 #[test]
7896 fn test_reject_funding_before_inbound_channel_accepted() {
7897         // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
7898         // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
7899         // the node operator before the counterparty sends a `FundingCreated` message. If a
7900         // `FundingCreated` message is received before the channel is accepted, it should be rejected
7901         // and the channel should be closed.
7902         let mut manually_accept_conf = UserConfig::default();
7903         manually_accept_conf.manually_accept_inbound_channels = true;
7904         let chanmon_cfgs = create_chanmon_cfgs(2);
7905         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7906         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7907         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7908
7909         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7910         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7911         let temp_channel_id = res.temporary_channel_id;
7912
7913         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7914
7915         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
7916         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7917
7918         // Clear the `Event::OpenChannelRequest` event without responding to the request.
7919         nodes[1].node.get_and_clear_pending_events();
7920
7921         // Get the `AcceptChannel` message of `nodes[1]` without calling
7922         // `ChannelManager::accept_inbound_channel`, which generates a
7923         // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
7924         // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
7925         // succeed when `nodes[0]` is passed to it.
7926         let accept_chan_msg = {
7927                 let mut node_1_per_peer_lock;
7928                 let mut node_1_peer_state_lock;
7929                 let channel =  get_channel_ref!(&nodes[1], nodes[0], node_1_per_peer_lock, node_1_peer_state_lock, temp_channel_id);
7930                 channel.get_accept_channel_message()
7931         };
7932         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
7933
7934         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
7935
7936         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
7937         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
7938
7939         // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
7940         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
7941
7942         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7943         assert_eq!(close_msg_ev.len(), 1);
7944
7945         let expected_err = "FundingCreated message received before the channel was accepted";
7946         match close_msg_ev[0] {
7947                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
7948                         assert_eq!(msg.channel_id, temp_channel_id);
7949                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7950                         assert_eq!(msg.data, expected_err);
7951                 }
7952                 _ => panic!("Unexpected event"),
7953         }
7954
7955         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
7956 }
7957
7958 #[test]
7959 fn test_can_not_accept_inbound_channel_twice() {
7960         let mut manually_accept_conf = UserConfig::default();
7961         manually_accept_conf.manually_accept_inbound_channels = true;
7962         let chanmon_cfgs = create_chanmon_cfgs(2);
7963         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7964         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7965         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7966
7967         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7968         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7969
7970         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7971
7972         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7973         // accepting the inbound channel request.
7974         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7975
7976         let events = nodes[1].node.get_and_clear_pending_events();
7977         match events[0] {
7978                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7979                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7980                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7981                         match api_res {
7982                                 Err(APIError::APIMisuseError { err }) => {
7983                                         assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
7984                                 },
7985                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7986                                 Err(_) => panic!("Unexpected Error"),
7987                         }
7988                 }
7989                 _ => panic!("Unexpected event"),
7990         }
7991
7992         // Ensure that the channel wasn't closed after attempting to accept it twice.
7993         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7994         assert_eq!(accept_msg_ev.len(), 1);
7995
7996         match accept_msg_ev[0] {
7997                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7998                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7999                 }
8000                 _ => panic!("Unexpected event"),
8001         }
8002 }
8003
8004 #[test]
8005 fn test_can_not_accept_unknown_inbound_channel() {
8006         let chanmon_cfg = create_chanmon_cfgs(2);
8007         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8008         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8009         let nodes = create_network(2, &node_cfg, &node_chanmgr);
8010
8011         let unknown_channel_id = [0; 32];
8012         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8013         match api_res {
8014                 Err(APIError::ChannelUnavailable { err }) => {
8015                         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()));
8016                 },
8017                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8018                 Err(_) => panic!("Unexpected Error"),
8019         }
8020 }
8021
8022 #[test]
8023 fn test_onion_value_mpp_set_calculation() {
8024         // Test that we use the onion value `amt_to_forward` when
8025         // calculating whether we've reached the `total_msat` of an MPP
8026         // by having a routing node forward more than `amt_to_forward`
8027         // and checking that the receiving node doesn't generate
8028         // a PaymentClaimable event too early
8029         let node_count = 4;
8030         let chanmon_cfgs = create_chanmon_cfgs(node_count);
8031         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8032         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8033         let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8034
8035         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8036         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8037         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8038         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8039
8040         let total_msat = 100_000;
8041         let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
8042         let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
8043         let sample_path = route.paths.pop().unwrap();
8044
8045         let mut path_1 = sample_path.clone();
8046         path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
8047         path_1.hops[0].short_channel_id = chan_1_id;
8048         path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
8049         path_1.hops[1].short_channel_id = chan_3_id;
8050         path_1.hops[1].fee_msat = 100_000;
8051         route.paths.push(path_1);
8052
8053         let mut path_2 = sample_path.clone();
8054         path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
8055         path_2.hops[0].short_channel_id = chan_2_id;
8056         path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
8057         path_2.hops[1].short_channel_id = chan_4_id;
8058         path_2.hops[1].fee_msat = 1_000;
8059         route.paths.push(path_2);
8060
8061         // Send payment
8062         let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
8063         let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
8064                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8065         nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
8066                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8067         check_added_monitors!(nodes[0], expected_paths.len());
8068
8069         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8070         assert_eq!(events.len(), expected_paths.len());
8071
8072         // First path
8073         let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8074         let mut payment_event = SendEvent::from_event(ev);
8075         let mut prev_node = &nodes[0];
8076
8077         for (idx, &node) in expected_paths[0].iter().enumerate() {
8078                 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8079
8080                 if idx == 0 { // routing node
8081                         let session_priv = [3; 32];
8082                         let height = nodes[0].best_block_info().1;
8083                         let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8084                         let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8085                         let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8086                                 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8087                         // Edit amt_to_forward to simulate the sender having set
8088                         // the final amount and the routing node taking less fee
8089                         onion_payloads[1].amt_to_forward = 99_000;
8090                         let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
8091                         payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8092                 }
8093
8094                 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8095                 check_added_monitors!(node, 0);
8096                 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8097                 expect_pending_htlcs_forwardable!(node);
8098
8099                 if idx == 0 {
8100                         let mut events_2 = node.node.get_and_clear_pending_msg_events();
8101                         assert_eq!(events_2.len(), 1);
8102                         check_added_monitors!(node, 1);
8103                         payment_event = SendEvent::from_event(events_2.remove(0));
8104                         assert_eq!(payment_event.msgs.len(), 1);
8105                 } else {
8106                         let events_2 = node.node.get_and_clear_pending_events();
8107                         assert!(events_2.is_empty());
8108                 }
8109
8110                 prev_node = node;
8111         }
8112
8113         // Second path
8114         let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8115         pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8116
8117         claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8118 }
8119
8120 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8121
8122         let routing_node_count = msat_amounts.len();
8123         let node_count = routing_node_count + 2;
8124
8125         let chanmon_cfgs = create_chanmon_cfgs(node_count);
8126         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8127         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8128         let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8129
8130         let src_idx = 0;
8131         let dst_idx = 1;
8132
8133         // Create channels for each amount
8134         let mut expected_paths = Vec::with_capacity(routing_node_count);
8135         let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8136         let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8137         for i in 0..routing_node_count {
8138                 let routing_node = 2 + i;
8139                 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8140                 src_chan_ids.push(src_chan_id);
8141                 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8142                 dst_chan_ids.push(dst_chan_id);
8143                 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8144                 expected_paths.push(path);
8145         }
8146         let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8147
8148         // Create a route for each amount
8149         let example_amount = 100000;
8150         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);
8151         let sample_path = route.paths.pop().unwrap();
8152         for i in 0..routing_node_count {
8153                 let routing_node = 2 + i;
8154                 let mut path = sample_path.clone();
8155                 path.hops[0].pubkey = nodes[routing_node].node.get_our_node_id();
8156                 path.hops[0].short_channel_id = src_chan_ids[i];
8157                 path.hops[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8158                 path.hops[1].short_channel_id = dst_chan_ids[i];
8159                 path.hops[1].fee_msat = msat_amounts[i];
8160                 route.paths.push(path);
8161         }
8162
8163         // Send payment with manually set total_msat
8164         let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8165         let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8166                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8167         nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8168                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8169         check_added_monitors!(nodes[src_idx], expected_paths.len());
8170
8171         let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8172         assert_eq!(events.len(), expected_paths.len());
8173         let mut amount_received = 0;
8174         for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8175                 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8176
8177                 let current_path_amount = msat_amounts[path_idx];
8178                 amount_received += current_path_amount;
8179                 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8180                 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8181         }
8182
8183         claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8184 }
8185
8186 #[test]
8187 fn test_overshoot_mpp() {
8188         do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8189         do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8190 }
8191
8192 #[test]
8193 fn test_simple_mpp() {
8194         // Simple test of sending a multi-path payment.
8195         let chanmon_cfgs = create_chanmon_cfgs(4);
8196         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8197         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8198         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8199
8200         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8201         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8202         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8203         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8204
8205         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8206         let path = route.paths[0].clone();
8207         route.paths.push(path);
8208         route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
8209         route.paths[0].hops[0].short_channel_id = chan_1_id;
8210         route.paths[0].hops[1].short_channel_id = chan_3_id;
8211         route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
8212         route.paths[1].hops[0].short_channel_id = chan_2_id;
8213         route.paths[1].hops[1].short_channel_id = chan_4_id;
8214         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8215         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8216 }
8217
8218 #[test]
8219 fn test_preimage_storage() {
8220         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8221         let chanmon_cfgs = create_chanmon_cfgs(2);
8222         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8223         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8224         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8225
8226         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8227
8228         {
8229                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8230                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8231                 nodes[0].node.send_payment_with_route(&route, payment_hash,
8232                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8233                 check_added_monitors!(nodes[0], 1);
8234                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8235                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8236                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8237                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8238         }
8239         // Note that after leaving the above scope we have no knowledge of any arguments or return
8240         // values from previous calls.
8241         expect_pending_htlcs_forwardable!(nodes[1]);
8242         let events = nodes[1].node.get_and_clear_pending_events();
8243         assert_eq!(events.len(), 1);
8244         match events[0] {
8245                 Event::PaymentClaimable { ref purpose, .. } => {
8246                         match &purpose {
8247                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8248                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8249                                 },
8250                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8251                         }
8252                 },
8253                 _ => panic!("Unexpected event"),
8254         }
8255 }
8256
8257 #[test]
8258 #[allow(deprecated)]
8259 fn test_secret_timeout() {
8260         // Simple test of payment secret storage time outs. After
8261         // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8262         let chanmon_cfgs = create_chanmon_cfgs(2);
8263         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8264         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8265         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8266
8267         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8268
8269         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8270
8271         // We should fail to register the same payment hash twice, at least until we've connected a
8272         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8273         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8274                 assert_eq!(err, "Duplicate payment hash");
8275         } else { panic!(); }
8276         let mut block = {
8277                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8278                 Block {
8279                         header: BlockHeader {
8280                                 version: 0x2000000,
8281                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8282                                 merkle_root: TxMerkleNode::all_zeros(),
8283                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8284                         txdata: vec![],
8285                 }
8286         };
8287         connect_block(&nodes[1], &block);
8288         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8289                 assert_eq!(err, "Duplicate payment hash");
8290         } else { panic!(); }
8291
8292         // If we then connect the second block, we should be able to register the same payment hash
8293         // again (this time getting a new payment secret).
8294         block.header.prev_blockhash = block.header.block_hash();
8295         block.header.time += 1;
8296         connect_block(&nodes[1], &block);
8297         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8298         assert_ne!(payment_secret_1, our_payment_secret);
8299
8300         {
8301                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8302                 nodes[0].node.send_payment_with_route(&route, payment_hash,
8303                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(payment_hash.0)).unwrap();
8304                 check_added_monitors!(nodes[0], 1);
8305                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8306                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8307                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8308                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8309         }
8310         // Note that after leaving the above scope we have no knowledge of any arguments or return
8311         // values from previous calls.
8312         expect_pending_htlcs_forwardable!(nodes[1]);
8313         let events = nodes[1].node.get_and_clear_pending_events();
8314         assert_eq!(events.len(), 1);
8315         match events[0] {
8316                 Event::PaymentClaimable { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8317                         assert!(payment_preimage.is_none());
8318                         assert_eq!(payment_secret, our_payment_secret);
8319                         // We don't actually have the payment preimage with which to claim this payment!
8320                 },
8321                 _ => panic!("Unexpected event"),
8322         }
8323 }
8324
8325 #[test]
8326 fn test_bad_secret_hash() {
8327         // Simple test of unregistered payment hash/invalid payment secret handling
8328         let chanmon_cfgs = create_chanmon_cfgs(2);
8329         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8330         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8331         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8332
8333         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8334
8335         let random_payment_hash = PaymentHash([42; 32]);
8336         let random_payment_secret = PaymentSecret([43; 32]);
8337         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8338         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8339
8340         // All the below cases should end up being handled exactly identically, so we macro the
8341         // resulting events.
8342         macro_rules! handle_unknown_invalid_payment_data {
8343                 ($payment_hash: expr) => {
8344                         check_added_monitors!(nodes[0], 1);
8345                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8346                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8347                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8348                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8349
8350                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8351                         // again to process the pending backwards-failure of the HTLC
8352                         expect_pending_htlcs_forwardable!(nodes[1]);
8353                         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8354                         check_added_monitors!(nodes[1], 1);
8355
8356                         // We should fail the payment back
8357                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8358                         match events.pop().unwrap() {
8359                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8360                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8361                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8362                                 },
8363                                 _ => panic!("Unexpected event"),
8364                         }
8365                 }
8366         }
8367
8368         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8369         // Error data is the HTLC value (100,000) and current block height
8370         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8371
8372         // Send a payment with the right payment hash but the wrong payment secret
8373         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8374                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8375         handle_unknown_invalid_payment_data!(our_payment_hash);
8376         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8377
8378         // Send a payment with a random payment hash, but the right payment secret
8379         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8380                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8381         handle_unknown_invalid_payment_data!(random_payment_hash);
8382         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8383
8384         // Send a payment with a random payment hash and random payment secret
8385         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8386                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8387         handle_unknown_invalid_payment_data!(random_payment_hash);
8388         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8389 }
8390
8391 #[test]
8392 fn test_update_err_monitor_lockdown() {
8393         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8394         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8395         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8396         // error.
8397         //
8398         // This scenario may happen in a watchtower setup, where watchtower process a block height
8399         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8400         // commitment at same time.
8401
8402         let chanmon_cfgs = create_chanmon_cfgs(2);
8403         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8404         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8405         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8406
8407         // Create some initial channel
8408         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8409         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8410
8411         // Rebalance the network to generate htlc in the two directions
8412         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8413
8414         // Route a HTLC from node 0 to node 1 (but don't settle)
8415         let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8416
8417         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8418         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8419         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8420         let persister = test_utils::TestPersister::new();
8421         let watchtower = {
8422                 let new_monitor = {
8423                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8424                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8425                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8426                         assert!(new_monitor == *monitor);
8427                         new_monitor
8428                 };
8429                 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);
8430                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8431                 watchtower
8432         };
8433         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8434         let block = Block { header, txdata: vec![] };
8435         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8436         // transaction lock time requirements here.
8437         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8438         watchtower.chain_monitor.block_connected(&block, 200);
8439
8440         // Try to update ChannelMonitor
8441         nodes[1].node.claim_funds(preimage);
8442         check_added_monitors!(nodes[1], 1);
8443         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8444
8445         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8446         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8447         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8448         {
8449                 let mut node_0_per_peer_lock;
8450                 let mut node_0_peer_state_lock;
8451                 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8452                 if let Ok(update) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8453                         assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8454                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8455                 } else { assert!(false); }
8456         }
8457         // Our local monitor is in-sync and hasn't processed yet timeout
8458         check_added_monitors!(nodes[0], 1);
8459         let events = nodes[0].node.get_and_clear_pending_events();
8460         assert_eq!(events.len(), 1);
8461 }
8462
8463 #[test]
8464 fn test_concurrent_monitor_claim() {
8465         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8466         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8467         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8468         // state N+1 confirms. Alice claims output from state N+1.
8469
8470         let chanmon_cfgs = create_chanmon_cfgs(2);
8471         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8472         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8473         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8474
8475         // Create some initial channel
8476         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8477         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8478
8479         // Rebalance the network to generate htlc in the two directions
8480         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8481
8482         // Route a HTLC from node 0 to node 1 (but don't settle)
8483         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8484
8485         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8486         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8487         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8488         let persister = test_utils::TestPersister::new();
8489         let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8490                 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8491         );
8492         let watchtower_alice = {
8493                 let new_monitor = {
8494                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8495                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8496                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8497                         assert!(new_monitor == *monitor);
8498                         new_monitor
8499                 };
8500                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &alice_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8501                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8502                 watchtower
8503         };
8504         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8505         let block = Block { header, txdata: vec![] };
8506         // Make Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8507         // requirements here.
8508         const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8509         alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8510         watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8511
8512         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8513         let alice_state = {
8514                 let mut txn = alice_broadcaster.txn_broadcast();
8515                 assert_eq!(txn.len(), 2);
8516                 txn.remove(0)
8517         };
8518
8519         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8520         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8521         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8522         let persister = test_utils::TestPersister::new();
8523         let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8524         let watchtower_bob = {
8525                 let new_monitor = {
8526                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8527                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8528                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8529                         assert!(new_monitor == *monitor);
8530                         new_monitor
8531                 };
8532                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8533                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8534                 watchtower
8535         };
8536         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8537         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, HTLC_TIMEOUT_BROADCAST - 1);
8538
8539         // Route another payment to generate another update with still previous HTLC pending
8540         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8541         nodes[1].node.send_payment_with_route(&route, payment_hash,
8542                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8543         check_added_monitors!(nodes[1], 1);
8544
8545         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8546         assert_eq!(updates.update_add_htlcs.len(), 1);
8547         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8548         {
8549                 let mut node_0_per_peer_lock;
8550                 let mut node_0_peer_state_lock;
8551                 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8552                 if let Ok(update) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8553                         // Watchtower Alice should already have seen the block and reject the update
8554                         assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8555                         assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8556                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8557                 } else { assert!(false); }
8558         }
8559         // Our local monitor is in-sync and hasn't processed yet timeout
8560         check_added_monitors!(nodes[0], 1);
8561
8562         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8563         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8564         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, HTLC_TIMEOUT_BROADCAST);
8565
8566         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8567         let bob_state_y;
8568         {
8569                 let mut txn = bob_broadcaster.txn_broadcast();
8570                 assert_eq!(txn.len(), 2);
8571                 bob_state_y = txn.remove(0);
8572         };
8573
8574         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8575         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8576         let height = HTLC_TIMEOUT_BROADCAST + 1;
8577         connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
8578         check_closed_broadcast(&nodes[0], 1, true);
8579         check_closed_event(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false);
8580         watchtower_alice.chain_monitor.block_connected(&Block { header, txdata: vec![bob_state_y.clone()] }, height);
8581         check_added_monitors(&nodes[0], 1);
8582         {
8583                 let htlc_txn = alice_broadcaster.txn_broadcast();
8584                 assert_eq!(htlc_txn.len(), 2);
8585                 check_spends!(htlc_txn[0], bob_state_y);
8586                 // Alice doesn't clean up the old HTLC claim since it hasn't seen a conflicting spend for
8587                 // it. However, she should, because it now has an invalid parent.
8588                 check_spends!(htlc_txn[1], alice_state);
8589         }
8590 }
8591
8592 #[test]
8593 fn test_pre_lockin_no_chan_closed_update() {
8594         // Test that if a peer closes a channel in response to a funding_created message we don't
8595         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8596         // message).
8597         //
8598         // Doing so would imply a channel monitor update before the initial channel monitor
8599         // registration, violating our API guarantees.
8600         //
8601         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8602         // then opening a second channel with the same funding output as the first (which is not
8603         // rejected because the first channel does not exist in the ChannelManager) and closing it
8604         // before receiving funding_signed.
8605         let chanmon_cfgs = create_chanmon_cfgs(2);
8606         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8607         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8608         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8609
8610         // Create an initial channel
8611         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8612         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8613         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8614         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8615         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8616
8617         // Move the first channel through the funding flow...
8618         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8619
8620         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8621         check_added_monitors!(nodes[0], 0);
8622
8623         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8624         let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8625         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8626         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8627         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true);
8628 }
8629
8630 #[test]
8631 fn test_htlc_no_detection() {
8632         // This test is a mutation to underscore the detection logic bug we had
8633         // before #653. HTLC value routed is above the remaining balance, thus
8634         // inverting HTLC and `to_remote` output. HTLC will come second and
8635         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8636         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8637         // outputs order detection for correct spending children filtring.
8638
8639         let chanmon_cfgs = create_chanmon_cfgs(2);
8640         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8641         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8642         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8643
8644         // Create some initial channels
8645         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8646
8647         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8648         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8649         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8650         assert_eq!(local_txn[0].input.len(), 1);
8651         assert_eq!(local_txn[0].output.len(), 3);
8652         check_spends!(local_txn[0], chan_1.3);
8653
8654         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8655         let header = 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, txdata: vec![local_txn[0].clone()] });
8657         // We deliberately connect the local tx twice as this should provoke a failure calling
8658         // this test before #653 fix.
8659         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);
8660         check_closed_broadcast!(nodes[0], true);
8661         check_added_monitors!(nodes[0], 1);
8662         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8663         connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8664
8665         let htlc_timeout = {
8666                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8667                 assert_eq!(node_txn.len(), 1);
8668                 assert_eq!(node_txn[0].input.len(), 1);
8669                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8670                 check_spends!(node_txn[0], local_txn[0]);
8671                 node_txn[0].clone()
8672         };
8673
8674         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8675         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8676         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8677         expect_payment_failed!(nodes[0], our_payment_hash, false);
8678 }
8679
8680 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8681         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8682         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8683         // Carol, Alice would be the upstream node, and Carol the downstream.)
8684         //
8685         // Steps of the test:
8686         // 1) Alice sends a HTLC to Carol through Bob.
8687         // 2) Carol doesn't settle the HTLC.
8688         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8689         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8690         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8691         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8692         // 5) Carol release the preimage to Bob off-chain.
8693         // 6) Bob claims the offered output on the broadcasted commitment.
8694         let chanmon_cfgs = create_chanmon_cfgs(3);
8695         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8696         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8697         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8698
8699         // Create some initial channels
8700         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8701         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8702
8703         // Steps (1) and (2):
8704         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8705         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8706
8707         // Check that Alice's commitment transaction now contains an output for this HTLC.
8708         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8709         check_spends!(alice_txn[0], chan_ab.3);
8710         assert_eq!(alice_txn[0].output.len(), 2);
8711         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8712         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8713         assert_eq!(alice_txn.len(), 2);
8714
8715         // Steps (3) and (4):
8716         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8717         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8718         let mut force_closing_node = 0; // Alice force-closes
8719         let mut counterparty_node = 1; // Bob if Alice force-closes
8720
8721         // Bob force-closes
8722         if !broadcast_alice {
8723                 force_closing_node = 1;
8724                 counterparty_node = 0;
8725         }
8726         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8727         check_closed_broadcast!(nodes[force_closing_node], true);
8728         check_added_monitors!(nodes[force_closing_node], 1);
8729         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8730         if go_onchain_before_fulfill {
8731                 let txn_to_broadcast = match broadcast_alice {
8732                         true => alice_txn.clone(),
8733                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8734                 };
8735                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8736                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8737                 if broadcast_alice {
8738                         check_closed_broadcast!(nodes[1], true);
8739                         check_added_monitors!(nodes[1], 1);
8740                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8741                 }
8742         }
8743
8744         // Step (5):
8745         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8746         // process of removing the HTLC from their commitment transactions.
8747         nodes[2].node.claim_funds(payment_preimage);
8748         check_added_monitors!(nodes[2], 1);
8749         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8750
8751         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8752         assert!(carol_updates.update_add_htlcs.is_empty());
8753         assert!(carol_updates.update_fail_htlcs.is_empty());
8754         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8755         assert!(carol_updates.update_fee.is_none());
8756         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8757
8758         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8759         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8760         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8761         if !go_onchain_before_fulfill && broadcast_alice {
8762                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8763                 assert_eq!(events.len(), 1);
8764                 match events[0] {
8765                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8766                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8767                         },
8768                         _ => panic!("Unexpected event"),
8769                 };
8770         }
8771         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8772         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8773         // Carol<->Bob's updated commitment transaction info.
8774         check_added_monitors!(nodes[1], 2);
8775
8776         let events = nodes[1].node.get_and_clear_pending_msg_events();
8777         assert_eq!(events.len(), 2);
8778         let bob_revocation = match events[0] {
8779                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8780                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8781                         (*msg).clone()
8782                 },
8783                 _ => panic!("Unexpected event"),
8784         };
8785         let bob_updates = match events[1] {
8786                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8787                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8788                         (*updates).clone()
8789                 },
8790                 _ => panic!("Unexpected event"),
8791         };
8792
8793         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8794         check_added_monitors!(nodes[2], 1);
8795         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8796         check_added_monitors!(nodes[2], 1);
8797
8798         let events = nodes[2].node.get_and_clear_pending_msg_events();
8799         assert_eq!(events.len(), 1);
8800         let carol_revocation = match events[0] {
8801                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8802                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8803                         (*msg).clone()
8804                 },
8805                 _ => panic!("Unexpected event"),
8806         };
8807         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8808         check_added_monitors!(nodes[1], 1);
8809
8810         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8811         // here's where we put said channel's commitment tx on-chain.
8812         let mut txn_to_broadcast = alice_txn.clone();
8813         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8814         if !go_onchain_before_fulfill {
8815                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8816                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8817                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8818                 if broadcast_alice {
8819                         check_closed_broadcast!(nodes[1], true);
8820                         check_added_monitors!(nodes[1], 1);
8821                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8822                 }
8823                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8824                 if broadcast_alice {
8825                         assert_eq!(bob_txn.len(), 1);
8826                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8827                 } else {
8828                         assert_eq!(bob_txn.len(), 2);
8829                         check_spends!(bob_txn[0], chan_ab.3);
8830                 }
8831         }
8832
8833         // Step (6):
8834         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8835         // broadcasted commitment transaction.
8836         {
8837                 let script_weight = match broadcast_alice {
8838                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8839                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8840                 };
8841                 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8842                 // Bob force-closed and broadcasts the commitment transaction along with a
8843                 // HTLC-output-claiming transaction.
8844                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8845                 if broadcast_alice {
8846                         assert_eq!(bob_txn.len(), 1);
8847                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8848                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8849                 } else {
8850                         assert_eq!(bob_txn.len(), 2);
8851                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8852                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8853                 }
8854         }
8855 }
8856
8857 #[test]
8858 fn test_onchain_htlc_settlement_after_close() {
8859         do_test_onchain_htlc_settlement_after_close(true, true);
8860         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8861         do_test_onchain_htlc_settlement_after_close(true, false);
8862         do_test_onchain_htlc_settlement_after_close(false, false);
8863 }
8864
8865 #[test]
8866 fn test_duplicate_temporary_channel_id_from_different_peers() {
8867         // Tests that we can accept two different `OpenChannel` requests with the same
8868         // `temporary_channel_id`, as long as they are from different peers.
8869         let chanmon_cfgs = create_chanmon_cfgs(3);
8870         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8871         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8872         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8873
8874         // Create an first channel channel
8875         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8876         let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8877
8878         // Create an second channel
8879         nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8880         let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8881
8882         // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8883         // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8884         open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8885
8886         // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8887         // `temporary_channel_id` as they are from different peers.
8888         nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8889         {
8890                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8891                 assert_eq!(events.len(), 1);
8892                 match &events[0] {
8893                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8894                                 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8895                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8896                         },
8897                         _ => panic!("Unexpected event"),
8898                 }
8899         }
8900
8901         nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8902         {
8903                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8904                 assert_eq!(events.len(), 1);
8905                 match &events[0] {
8906                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8907                                 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8908                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8909                         },
8910                         _ => panic!("Unexpected event"),
8911                 }
8912         }
8913 }
8914
8915 #[test]
8916 fn test_duplicate_chan_id() {
8917         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8918         // already open we reject it and keep the old channel.
8919         //
8920         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8921         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8922         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8923         // updating logic for the existing channel.
8924         let chanmon_cfgs = create_chanmon_cfgs(2);
8925         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8926         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8927         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8928
8929         // Create an initial channel
8930         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8931         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8932         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8933         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()));
8934
8935         // Try to create a second channel with the same temporary_channel_id as the first and check
8936         // that it is rejected.
8937         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8938         {
8939                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8940                 assert_eq!(events.len(), 1);
8941                 match events[0] {
8942                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8943                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8944                                 // first (valid) and second (invalid) channels are closed, given they both have
8945                                 // the same non-temporary channel_id. However, currently we do not, so we just
8946                                 // move forward with it.
8947                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8948                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8949                         },
8950                         _ => panic!("Unexpected event"),
8951                 }
8952         }
8953
8954         // Move the first channel through the funding flow...
8955         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8956
8957         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8958         check_added_monitors!(nodes[0], 0);
8959
8960         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8961         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8962         {
8963                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8964                 assert_eq!(added_monitors.len(), 1);
8965                 assert_eq!(added_monitors[0].0, funding_output);
8966                 added_monitors.clear();
8967         }
8968         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
8969
8970         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8971
8972         let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8973         let channel_id = funding_outpoint.to_channel_id();
8974
8975         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8976         // temporary one).
8977
8978         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8979         // Technically this is allowed by the spec, but we don't support it and there's little reason
8980         // to. Still, it shouldn't cause any other issues.
8981         open_chan_msg.temporary_channel_id = channel_id;
8982         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8983         {
8984                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8985                 assert_eq!(events.len(), 1);
8986                 match events[0] {
8987                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8988                                 // Technically, at this point, nodes[1] would be justified in thinking both
8989                                 // channels are closed, but currently we do not, so we just move forward with it.
8990                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8991                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8992                         },
8993                         _ => panic!("Unexpected event"),
8994                 }
8995         }
8996
8997         // Now try to create a second channel which has a duplicate funding output.
8998         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8999         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9000         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
9001         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()));
9002         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9003
9004         let funding_created = {
9005                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9006                 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9007                 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
9008                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9009                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9010                 // channelmanager in a possibly nonsense state instead).
9011                 let mut as_chan = a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
9012                 let logger = test_utils::TestLogger::new();
9013                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9014         };
9015         check_added_monitors!(nodes[0], 0);
9016         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9017         // At this point we'll look up if the channel_id is present and immediately fail the channel
9018         // without trying to persist the `ChannelMonitor`.
9019         check_added_monitors!(nodes[1], 0);
9020
9021         // ...still, nodes[1] will reject the duplicate channel.
9022         {
9023                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9024                 assert_eq!(events.len(), 1);
9025                 match events[0] {
9026                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9027                                 // Technically, at this point, nodes[1] would be justified in thinking both
9028                                 // channels are closed, but currently we do not, so we just move forward with it.
9029                                 assert_eq!(msg.channel_id, channel_id);
9030                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9031                         },
9032                         _ => panic!("Unexpected event"),
9033                 }
9034         }
9035
9036         // finally, finish creating the original channel and send a payment over it to make sure
9037         // everything is functional.
9038         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9039         {
9040                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9041                 assert_eq!(added_monitors.len(), 1);
9042                 assert_eq!(added_monitors[0].0, funding_output);
9043                 added_monitors.clear();
9044         }
9045         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9046
9047         let events_4 = nodes[0].node.get_and_clear_pending_events();
9048         assert_eq!(events_4.len(), 0);
9049         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9050         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9051
9052         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9053         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9054         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9055
9056         send_payment(&nodes[0], &[&nodes[1]], 8000000);
9057 }
9058
9059 #[test]
9060 fn test_error_chans_closed() {
9061         // Test that we properly handle error messages, closing appropriate channels.
9062         //
9063         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9064         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9065         // we can test various edge cases around it to ensure we don't regress.
9066         let chanmon_cfgs = create_chanmon_cfgs(3);
9067         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9068         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9069         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9070
9071         // Create some initial channels
9072         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9073         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9074         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
9075
9076         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9077         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9078         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9079
9080         // Closing a channel from a different peer has no effect
9081         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9082         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9083
9084         // Closing one channel doesn't impact others
9085         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9086         check_added_monitors!(nodes[0], 1);
9087         check_closed_broadcast!(nodes[0], false);
9088         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
9089         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9090         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9091         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);
9092         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);
9093
9094         // A null channel ID should close all channels
9095         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9096         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9097         check_added_monitors!(nodes[0], 2);
9098         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
9099         let events = nodes[0].node.get_and_clear_pending_msg_events();
9100         assert_eq!(events.len(), 2);
9101         match events[0] {
9102                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9103                         assert_eq!(msg.contents.flags & 2, 2);
9104                 },
9105                 _ => panic!("Unexpected event"),
9106         }
9107         match events[1] {
9108                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9109                         assert_eq!(msg.contents.flags & 2, 2);
9110                 },
9111                 _ => panic!("Unexpected event"),
9112         }
9113         // Note that at this point users of a standard PeerHandler will end up calling
9114         // peer_disconnected.
9115         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9116         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9117
9118         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9119         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9120         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9121 }
9122
9123 #[test]
9124 fn test_invalid_funding_tx() {
9125         // Test that we properly handle invalid funding transactions sent to us from a peer.
9126         //
9127         // Previously, all other major lightning implementations had failed to properly sanitize
9128         // funding transactions from their counterparties, leading to a multi-implementation critical
9129         // security vulnerability (though we always sanitized properly, we've previously had
9130         // un-released crashes in the sanitization process).
9131         //
9132         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9133         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9134         // gave up on it. We test this here by generating such a transaction.
9135         let chanmon_cfgs = create_chanmon_cfgs(2);
9136         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9137         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9138         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9139
9140         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9141         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()));
9142         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()));
9143
9144         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9145
9146         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9147         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9148         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9149         // its length.
9150         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9151         let wit_program_script: Script = wit_program.into();
9152         for output in tx.output.iter_mut() {
9153                 // Make the confirmed funding transaction have a bogus script_pubkey
9154                 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9155         }
9156
9157         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9158         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()));
9159         check_added_monitors!(nodes[1], 1);
9160         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9161
9162         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()));
9163         check_added_monitors!(nodes[0], 1);
9164         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9165
9166         let events_1 = nodes[0].node.get_and_clear_pending_events();
9167         assert_eq!(events_1.len(), 0);
9168
9169         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9170         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9171         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9172
9173         let expected_err = "funding tx had wrong script/value or output index";
9174         confirm_transaction_at(&nodes[1], &tx, 1);
9175         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9176         check_added_monitors!(nodes[1], 1);
9177         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9178         assert_eq!(events_2.len(), 1);
9179         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9180                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9181                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9182                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9183                 } else { panic!(); }
9184         } else { panic!(); }
9185         assert_eq!(nodes[1].node.list_channels().len(), 0);
9186
9187         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9188         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9189         // as its not 32 bytes long.
9190         let mut spend_tx = Transaction {
9191                 version: 2i32, lock_time: PackedLockTime::ZERO,
9192                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9193                         previous_output: BitcoinOutPoint {
9194                                 txid: tx.txid(),
9195                                 vout: idx as u32,
9196                         },
9197                         script_sig: Script::new(),
9198                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9199                         witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9200                 }).collect(),
9201                 output: vec![TxOut {
9202                         value: 1000,
9203                         script_pubkey: Script::new(),
9204                 }]
9205         };
9206         check_spends!(spend_tx, tx);
9207         mine_transaction(&nodes[1], &spend_tx);
9208 }
9209
9210 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9211         // In the first version of the chain::Confirm interface, after a refactor was made to not
9212         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9213         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9214         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9215         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9216         // spending transaction until height N+1 (or greater). This was due to the way
9217         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9218         // spending transaction at the height the input transaction was confirmed at, not whether we
9219         // should broadcast a spending transaction at the current height.
9220         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9221         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9222         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9223         // until we learned about an additional block.
9224         //
9225         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9226         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9227         let chanmon_cfgs = create_chanmon_cfgs(3);
9228         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9229         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9230         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9231         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9232
9233         create_announced_chan_between_nodes(&nodes, 0, 1);
9234         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9235         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9236         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9237         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9238
9239         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9240         check_closed_broadcast!(nodes[1], true);
9241         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9242         check_added_monitors!(nodes[1], 1);
9243         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9244         assert_eq!(node_txn.len(), 1);
9245
9246         let conf_height = nodes[1].best_block_info().1;
9247         if !test_height_before_timelock {
9248                 connect_blocks(&nodes[1], 24 * 6);
9249         }
9250         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9251                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9252         if test_height_before_timelock {
9253                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9254                 // generate any events or broadcast any transactions
9255                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9256                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9257         } else {
9258                 // We should broadcast an HTLC transaction spending our funding transaction first
9259                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9260                 assert_eq!(spending_txn.len(), 2);
9261                 assert_eq!(spending_txn[0].txid(), node_txn[0].txid());
9262                 check_spends!(spending_txn[1], node_txn[0]);
9263                 // We should also generate a SpendableOutputs event with the to_self output (as its
9264                 // timelock is up).
9265                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9266                 assert_eq!(descriptor_spend_txn.len(), 1);
9267
9268                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9269                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9270                 // additional block built on top of the current chain.
9271                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9272                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9273                 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 }]);
9274                 check_added_monitors!(nodes[1], 1);
9275
9276                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9277                 assert!(updates.update_add_htlcs.is_empty());
9278                 assert!(updates.update_fulfill_htlcs.is_empty());
9279                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9280                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9281                 assert!(updates.update_fee.is_none());
9282                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9283                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9284                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9285         }
9286 }
9287
9288 #[test]
9289 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9290         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9291         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9292 }
9293
9294 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9295         let chanmon_cfgs = create_chanmon_cfgs(2);
9296         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9297         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9298         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9299
9300         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9301
9302         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9303                 .with_features(nodes[1].node.invoice_features());
9304         let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9305
9306         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9307
9308         {
9309                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9310                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9311                 check_added_monitors!(nodes[0], 1);
9312                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9313                 assert_eq!(events.len(), 1);
9314                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9315                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9316                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9317         }
9318         expect_pending_htlcs_forwardable!(nodes[1]);
9319         expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9320
9321         {
9322                 // Note that we use a different PaymentId here to allow us to duplicativly pay
9323                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9324                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9325                 check_added_monitors!(nodes[0], 1);
9326                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9327                 assert_eq!(events.len(), 1);
9328                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9329                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9330                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9331                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9332                 // assume the second is a privacy attack (no longer particularly relevant
9333                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9334                 // the first HTLC delivered above.
9335         }
9336
9337         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9338         nodes[1].node.process_pending_htlc_forwards();
9339
9340         if test_for_second_fail_panic {
9341                 // Now we go fail back the first HTLC from the user end.
9342                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9343
9344                 let expected_destinations = vec![
9345                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9346                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9347                 ];
9348                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],  expected_destinations);
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                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9354
9355                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9356                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9357                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9358
9359                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9360                 assert_eq!(failure_events.len(), 4);
9361                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9362                 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9363                 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9364                 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9365         } else {
9366                 // Let the second HTLC fail and claim the first
9367                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9368                 nodes[1].node.process_pending_htlc_forwards();
9369
9370                 check_added_monitors!(nodes[1], 1);
9371                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9372                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9373                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9374
9375                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9376
9377                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9378         }
9379 }
9380
9381 #[test]
9382 fn test_dup_htlc_second_fail_panic() {
9383         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9384         // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9385         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9386         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9387         do_test_dup_htlc_second_rejected(true);
9388 }
9389
9390 #[test]
9391 fn test_dup_htlc_second_rejected() {
9392         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9393         // simply reject the second HTLC but are still able to claim the first HTLC.
9394         do_test_dup_htlc_second_rejected(false);
9395 }
9396
9397 #[test]
9398 fn test_inconsistent_mpp_params() {
9399         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9400         // such HTLC and allow the second to stay.
9401         let chanmon_cfgs = create_chanmon_cfgs(4);
9402         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9403         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9404         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9405
9406         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9407         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9408         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9409         let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9410
9411         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9412                 .with_features(nodes[3].node.invoice_features());
9413         let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9414         assert_eq!(route.paths.len(), 2);
9415         route.paths.sort_by(|path_a, _| {
9416                 // Sort the path so that the path through nodes[1] comes first
9417                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9418                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9419         });
9420
9421         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9422
9423         let cur_height = nodes[0].best_block_info().1;
9424         let payment_id = PaymentId([42; 32]);
9425
9426         let session_privs = {
9427                 // We create a fake route here so that we start with three pending HTLCs, which we'll
9428                 // ultimately have, just not right away.
9429                 let mut dup_route = route.clone();
9430                 dup_route.paths.push(route.paths[1].clone());
9431                 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9432                         RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9433         };
9434         nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9435                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9436                 &None, session_privs[0]).unwrap();
9437         check_added_monitors!(nodes[0], 1);
9438
9439         {
9440                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9441                 assert_eq!(events.len(), 1);
9442                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9443         }
9444         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9445
9446         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9447                 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9448         check_added_monitors!(nodes[0], 1);
9449
9450         {
9451                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9452                 assert_eq!(events.len(), 1);
9453                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9454
9455                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9456                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9457
9458                 expect_pending_htlcs_forwardable!(nodes[2]);
9459                 check_added_monitors!(nodes[2], 1);
9460
9461                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9462                 assert_eq!(events.len(), 1);
9463                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9464
9465                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9466                 check_added_monitors!(nodes[3], 0);
9467                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9468
9469                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9470                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9471                 // post-payment_secrets) and fail back the new HTLC.
9472         }
9473         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9474         nodes[3].node.process_pending_htlc_forwards();
9475         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9476         nodes[3].node.process_pending_htlc_forwards();
9477
9478         check_added_monitors!(nodes[3], 1);
9479
9480         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9481         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9482         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9483
9484         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 }]);
9485         check_added_monitors!(nodes[2], 1);
9486
9487         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9488         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9489         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9490
9491         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9492
9493         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9494                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9495                 &None, session_privs[2]).unwrap();
9496         check_added_monitors!(nodes[0], 1);
9497
9498         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9499         assert_eq!(events.len(), 1);
9500         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9501
9502         do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9503         expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true);
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.hops[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 + 1.
9840                         Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 2), 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 +1 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 }