Verify channel-monitor processes blocks with skipped best_block
[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::sign::{ChannelSigner, EcdsaChannelSigner, EntropySource, SignerProvider};
21 use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose, ClosureReason, HTLCDestination, PaymentFailureReason};
22 use crate::ln::{ChannelId, 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, get_holder_selected_channel_reserve_satoshis, OutboundV1Channel, InboundV1Channel, COINBASE_MATURITY};
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::{DISCONNECT_PEER_AWAITING_RESPONSE_TICKS, 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, get_route, RouteParameters};
30 use crate::ln::features::{ChannelFeatures, ChannelTypeFeatures, NodeFeatures};
31 use crate::ln::msgs;
32 use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
33 use crate::util::test_channel_signer::TestChannelSigner;
34 use crate::util::test_utils::{self, WatchtowerPersister};
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, MaxDustHTLCExposure};
39
40 use bitcoin::hash_types::BlockHash;
41 use bitcoin::blockdata::script::{Builder, Script};
42 use bitcoin::blockdata::opcodes;
43 use bitcoin::blockdata::constants::genesis_block;
44 use bitcoin::network::constants::Network;
45 use bitcoin::{PackedLockTime, Sequence, Transaction, TxIn, TxOut, Witness};
46 use bitcoin::OutPoint as BitcoinOutPoint;
47
48 use bitcoin::secp256k1::Secp256k1;
49 use bitcoin::secp256k1::{PublicKey,SecretKey};
50
51 use regex;
52
53 use crate::io;
54 use crate::prelude::*;
55 use alloc::collections::BTreeSet;
56 use core::default::Default;
57 use core::iter::repeat;
58 use bitcoin::hashes::Hash;
59 use crate::sync::{Arc, Mutex, RwLock};
60
61 use crate::ln::functional_test_utils::*;
62 use crate::ln::chan_utils::CommitmentTransaction;
63
64 use super::channel::UNFUNDED_CHANNEL_AGE_LIMIT_TICKS;
65
66 #[test]
67 fn test_insane_channel_opens() {
68         // Stand up a network of 2 nodes
69         use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
70         let mut cfg = UserConfig::default();
71         cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
72         let chanmon_cfgs = create_chanmon_cfgs(2);
73         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
74         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
75         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
76
77         // Instantiate channel parameters where we push the maximum msats given our
78         // funding satoshis
79         let channel_value_sat = 31337; // same as funding satoshis
80         let channel_reserve_satoshis = get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
81         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
82
83         // Have node0 initiate a channel to node1 with aforementioned parameters
84         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
85
86         // Extract the channel open message from node0 to node1
87         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
88
89         // Test helper that asserts we get the correct error string given a mutator
90         // that supposedly makes the channel open message insane
91         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
92                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &message_mutator(open_channel_message.clone()));
93                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
94                 assert_eq!(msg_events.len(), 1);
95                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
96                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
97                         match action {
98                                 &ErrorAction::SendErrorMessage { .. } => {
99                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager", expected_regex, 1);
100                                 },
101                                 _ => panic!("unexpected event!"),
102                         }
103                 } else { assert!(false); }
104         };
105
106         use crate::ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
107
108         // Test all mutations that would make the channel open message insane
109         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 });
110         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 });
111
112         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
113
114         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 });
115
116         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
117
118         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 });
119
120         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 });
121
122         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
123
124         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
125 }
126
127 #[test]
128 fn test_funding_exceeds_no_wumbo_limit() {
129         // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
130         // them.
131         use crate::ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
132         let chanmon_cfgs = create_chanmon_cfgs(2);
133         let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
134         *node_cfgs[1].override_init_features.borrow_mut() = Some(channelmanager::provided_init_features(&test_default_channel_config()).clear_wumbo());
135         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
136         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
137
138         match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
139                 Err(APIError::APIMisuseError { err }) => {
140                         assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
141                 },
142                 _ => panic!()
143         }
144 }
145
146 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
147         // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
148         // but only for them. Because some LSPs do it with some level of trust of the clients (for a
149         // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
150         // in normal testing, we test it explicitly here.
151         let chanmon_cfgs = create_chanmon_cfgs(2);
152         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
153         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
154         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
155         let default_config = UserConfig::default();
156
157         // Have node0 initiate a channel to node1 with aforementioned parameters
158         let mut push_amt = 100_000_000;
159         let feerate_per_kw = 253;
160         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
161         push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(&channel_type_features) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
162         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
163
164         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();
165         let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
166         if !send_from_initiator {
167                 open_channel_message.channel_reserve_satoshis = 0;
168                 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
169         }
170         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
171
172         // Extract the channel accept message from node1 to node0
173         let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
174         if send_from_initiator {
175                 accept_channel_message.channel_reserve_satoshis = 0;
176                 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
177         }
178         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
179         {
180                 let sender_node = if send_from_initiator { &nodes[1] } else { &nodes[0] };
181                 let counterparty_node = if send_from_initiator { &nodes[0] } else { &nodes[1] };
182                 let mut sender_node_per_peer_lock;
183                 let mut sender_node_peer_state_lock;
184                 if send_from_initiator {
185                         let chan = get_inbound_v1_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
186                         chan.context.holder_selected_channel_reserve_satoshis = 0;
187                         chan.context.holder_max_htlc_value_in_flight_msat = 100_000_000;
188                 } else {
189                         let chan = get_outbound_v1_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
190                         chan.context.holder_selected_channel_reserve_satoshis = 0;
191                         chan.context.holder_max_htlc_value_in_flight_msat = 100_000_000;
192                 }
193         }
194
195         let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
196         let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
197         create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
198
199         // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
200         // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
201         if send_from_initiator {
202                 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
203                         // Note that for outbound channels we have to consider the commitment tx fee and the
204                         // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
205                         // well as an additional HTLC.
206                         - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, &channel_type_features));
207         } else {
208                 send_payment(&nodes[1], &[&nodes[0]], push_amt);
209         }
210 }
211
212 #[test]
213 fn test_counterparty_no_reserve() {
214         do_test_counterparty_no_reserve(true);
215         do_test_counterparty_no_reserve(false);
216 }
217
218 #[test]
219 fn test_async_inbound_update_fee() {
220         let chanmon_cfgs = create_chanmon_cfgs(2);
221         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
222         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
223         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
224         create_announced_chan_between_nodes(&nodes, 0, 1);
225
226         // balancing
227         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
228
229         // A                                        B
230         // update_fee                            ->
231         // send (1) commitment_signed            -.
232         //                                       <- update_add_htlc/commitment_signed
233         // send (2) RAA (awaiting remote revoke) -.
234         // (1) commitment_signed is delivered    ->
235         //                                       .- send (3) RAA (awaiting remote revoke)
236         // (2) RAA is delivered                  ->
237         //                                       .- send (4) commitment_signed
238         //                                       <- (3) RAA is delivered
239         // send (5) commitment_signed            -.
240         //                                       <- (4) commitment_signed is delivered
241         // send (6) RAA                          -.
242         // (5) commitment_signed is delivered    ->
243         //                                       <- RAA
244         // (6) RAA is delivered                  ->
245
246         // First nodes[0] generates an update_fee
247         {
248                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
249                 *feerate_lock += 20;
250         }
251         nodes[0].node.timer_tick_occurred();
252         check_added_monitors!(nodes[0], 1);
253
254         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
255         assert_eq!(events_0.len(), 1);
256         let (update_msg, commitment_signed) = match events_0[0] { // (1)
257                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
258                         (update_fee.as_ref(), commitment_signed)
259                 },
260                 _ => panic!("Unexpected event"),
261         };
262
263         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
264
265         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
266         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
267         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
268                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
269         check_added_monitors!(nodes[1], 1);
270
271         let payment_event = {
272                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
273                 assert_eq!(events_1.len(), 1);
274                 SendEvent::from_event(events_1.remove(0))
275         };
276         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
277         assert_eq!(payment_event.msgs.len(), 1);
278
279         // ...now when the messages get delivered everyone should be happy
280         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
281         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
282         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
283         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
284         check_added_monitors!(nodes[0], 1);
285
286         // deliver(1), generate (3):
287         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
288         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
289         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
290         check_added_monitors!(nodes[1], 1);
291
292         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
293         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
294         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
295         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
296         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
297         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
298         assert!(bs_update.update_fee.is_none()); // (4)
299         check_added_monitors!(nodes[1], 1);
300
301         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
302         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
303         assert!(as_update.update_add_htlcs.is_empty()); // (5)
304         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
305         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
306         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
307         assert!(as_update.update_fee.is_none()); // (5)
308         check_added_monitors!(nodes[0], 1);
309
310         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
311         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
312         // only (6) so get_event_msg's assert(len == 1) passes
313         check_added_monitors!(nodes[0], 1);
314
315         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
316         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
317         check_added_monitors!(nodes[1], 1);
318
319         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
320         check_added_monitors!(nodes[0], 1);
321
322         let events_2 = nodes[0].node.get_and_clear_pending_events();
323         assert_eq!(events_2.len(), 1);
324         match events_2[0] {
325                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
326                 _ => panic!("Unexpected event"),
327         }
328
329         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
330         check_added_monitors!(nodes[1], 1);
331 }
332
333 #[test]
334 fn test_update_fee_unordered_raa() {
335         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
336         // crash in an earlier version of the update_fee patch)
337         let chanmon_cfgs = create_chanmon_cfgs(2);
338         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
339         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
340         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
341         create_announced_chan_between_nodes(&nodes, 0, 1);
342
343         // balancing
344         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
345
346         // First nodes[0] generates an update_fee
347         {
348                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
349                 *feerate_lock += 20;
350         }
351         nodes[0].node.timer_tick_occurred();
352         check_added_monitors!(nodes[0], 1);
353
354         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
355         assert_eq!(events_0.len(), 1);
356         let update_msg = match events_0[0] { // (1)
357                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
358                         update_fee.as_ref()
359                 },
360                 _ => panic!("Unexpected event"),
361         };
362
363         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
364
365         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
366         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
367         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
368                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
369         check_added_monitors!(nodes[1], 1);
370
371         let payment_event = {
372                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
373                 assert_eq!(events_1.len(), 1);
374                 SendEvent::from_event(events_1.remove(0))
375         };
376         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
377         assert_eq!(payment_event.msgs.len(), 1);
378
379         // ...now when the messages get delivered everyone should be happy
380         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
381         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
382         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
383         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
384         check_added_monitors!(nodes[0], 1);
385
386         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
387         check_added_monitors!(nodes[1], 1);
388
389         // We can't continue, sadly, because our (1) now has a bogus signature
390 }
391
392 #[test]
393 fn test_multi_flight_update_fee() {
394         let chanmon_cfgs = create_chanmon_cfgs(2);
395         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
396         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
397         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
398         create_announced_chan_between_nodes(&nodes, 0, 1);
399
400         // A                                        B
401         // update_fee/commitment_signed          ->
402         //                                       .- send (1) RAA and (2) commitment_signed
403         // update_fee (never committed)          ->
404         // (3) update_fee                        ->
405         // We have to manually generate the above update_fee, it is allowed by the protocol but we
406         // don't track which updates correspond to which revoke_and_ack responses so we're in
407         // AwaitingRAA mode and will not generate the update_fee yet.
408         //                                       <- (1) RAA delivered
409         // (3) is generated and send (4) CS      -.
410         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
411         // know the per_commitment_point to use for it.
412         //                                       <- (2) commitment_signed delivered
413         // revoke_and_ack                        ->
414         //                                          B should send no response here
415         // (4) commitment_signed delivered       ->
416         //                                       <- RAA/commitment_signed delivered
417         // revoke_and_ack                        ->
418
419         // First nodes[0] generates an update_fee
420         let initial_feerate;
421         {
422                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
423                 initial_feerate = *feerate_lock;
424                 *feerate_lock = initial_feerate + 20;
425         }
426         nodes[0].node.timer_tick_occurred();
427         check_added_monitors!(nodes[0], 1);
428
429         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
430         assert_eq!(events_0.len(), 1);
431         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
432                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
433                         (update_fee.as_ref().unwrap(), commitment_signed)
434                 },
435                 _ => panic!("Unexpected event"),
436         };
437
438         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
439         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
440         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
441         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
442         check_added_monitors!(nodes[1], 1);
443
444         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
445         // transaction:
446         {
447                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
448                 *feerate_lock = initial_feerate + 40;
449         }
450         nodes[0].node.timer_tick_occurred();
451         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
452         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
453
454         // Create the (3) update_fee message that nodes[0] will generate before it does...
455         let mut update_msg_2 = msgs::UpdateFee {
456                 channel_id: update_msg_1.channel_id.clone(),
457                 feerate_per_kw: (initial_feerate + 30) as u32,
458         };
459
460         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
461
462         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
463         // Deliver (3)
464         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
465
466         // Deliver (1), generating (3) and (4)
467         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
468         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
469         check_added_monitors!(nodes[0], 1);
470         assert!(as_second_update.update_add_htlcs.is_empty());
471         assert!(as_second_update.update_fulfill_htlcs.is_empty());
472         assert!(as_second_update.update_fail_htlcs.is_empty());
473         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
474         // Check that the update_fee newly generated matches what we delivered:
475         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
476         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
477
478         // Deliver (2) commitment_signed
479         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
480         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
481         check_added_monitors!(nodes[0], 1);
482         // No commitment_signed so get_event_msg's assert(len == 1) passes
483
484         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
485         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
486         check_added_monitors!(nodes[1], 1);
487
488         // Delever (4)
489         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
490         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
491         check_added_monitors!(nodes[1], 1);
492
493         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
494         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
495         check_added_monitors!(nodes[0], 1);
496
497         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
498         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
499         // No commitment_signed so get_event_msg's assert(len == 1) passes
500         check_added_monitors!(nodes[0], 1);
501
502         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
503         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
504         check_added_monitors!(nodes[1], 1);
505 }
506
507 fn do_test_sanity_on_in_flight_opens(steps: u8) {
508         // Previously, we had issues deserializing channels when we hadn't connected the first block
509         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
510         // serialization round-trips and simply do steps towards opening a channel and then drop the
511         // Node objects.
512
513         let chanmon_cfgs = create_chanmon_cfgs(2);
514         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
515         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
516         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
517
518         if steps & 0b1000_0000 != 0{
519                 let block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
520                 connect_block(&nodes[0], &block);
521                 connect_block(&nodes[1], &block);
522         }
523
524         if steps & 0x0f == 0 { return; }
525         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
526         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
527
528         if steps & 0x0f == 1 { return; }
529         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
530         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
531
532         if steps & 0x0f == 2 { return; }
533         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
534
535         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
536
537         if steps & 0x0f == 3 { return; }
538         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
539         check_added_monitors!(nodes[0], 0);
540         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
541
542         if steps & 0x0f == 4 { return; }
543         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
544         {
545                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
546                 assert_eq!(added_monitors.len(), 1);
547                 assert_eq!(added_monitors[0].0, funding_output);
548                 added_monitors.clear();
549         }
550         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
551
552         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
553
554         if steps & 0x0f == 5 { return; }
555         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
556         {
557                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
558                 assert_eq!(added_monitors.len(), 1);
559                 assert_eq!(added_monitors[0].0, funding_output);
560                 added_monitors.clear();
561         }
562
563         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
564         let events_4 = nodes[0].node.get_and_clear_pending_events();
565         assert_eq!(events_4.len(), 0);
566
567         if steps & 0x0f == 6 { return; }
568         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
569
570         if steps & 0x0f == 7 { return; }
571         confirm_transaction_at(&nodes[0], &tx, 2);
572         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
573         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
574         expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
575 }
576
577 #[test]
578 fn test_sanity_on_in_flight_opens() {
579         do_test_sanity_on_in_flight_opens(0);
580         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
581         do_test_sanity_on_in_flight_opens(1);
582         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
583         do_test_sanity_on_in_flight_opens(2);
584         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
585         do_test_sanity_on_in_flight_opens(3);
586         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
587         do_test_sanity_on_in_flight_opens(4);
588         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
589         do_test_sanity_on_in_flight_opens(5);
590         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
591         do_test_sanity_on_in_flight_opens(6);
592         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
593         do_test_sanity_on_in_flight_opens(7);
594         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
595         do_test_sanity_on_in_flight_opens(8);
596         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
597 }
598
599 #[test]
600 fn test_update_fee_vanilla() {
601         let chanmon_cfgs = create_chanmon_cfgs(2);
602         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
603         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
604         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
605         create_announced_chan_between_nodes(&nodes, 0, 1);
606
607         {
608                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
609                 *feerate_lock += 25;
610         }
611         nodes[0].node.timer_tick_occurred();
612         check_added_monitors!(nodes[0], 1);
613
614         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
615         assert_eq!(events_0.len(), 1);
616         let (update_msg, commitment_signed) = match events_0[0] {
617                         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 } } => {
618                         (update_fee.as_ref(), commitment_signed)
619                 },
620                 _ => panic!("Unexpected event"),
621         };
622         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
623
624         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
625         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
626         check_added_monitors!(nodes[1], 1);
627
628         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
629         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
630         check_added_monitors!(nodes[0], 1);
631
632         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
633         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
634         // No commitment_signed so get_event_msg's assert(len == 1) passes
635         check_added_monitors!(nodes[0], 1);
636
637         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
638         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
639         check_added_monitors!(nodes[1], 1);
640 }
641
642 #[test]
643 fn test_update_fee_that_funder_cannot_afford() {
644         let chanmon_cfgs = create_chanmon_cfgs(2);
645         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
646         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
647         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
648         let channel_value = 5000;
649         let push_sats = 700;
650         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000);
651         let channel_id = chan.2;
652         let secp_ctx = Secp256k1::new();
653         let default_config = UserConfig::default();
654         let bs_channel_reserve_sats = get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
655
656         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
657
658         // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
659         // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
660         // calculate two different feerates here - the expected local limit as well as the expected
661         // remote limit.
662         let feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / (commitment_tx_base_weight(&channel_type_features) + CONCURRENT_INBOUND_HTLC_FEE_BUFFER as u64 * COMMITMENT_TX_WEIGHT_PER_HTLC)) as u32;
663         let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(&channel_type_features)) as u32;
664         {
665                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
666                 *feerate_lock = feerate;
667         }
668         nodes[0].node.timer_tick_occurred();
669         check_added_monitors!(nodes[0], 1);
670         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
671
672         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
673
674         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
675
676         // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
677         {
678                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
679
680                 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
681                 assert_eq!(commitment_tx.output.len(), 2);
682                 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, &channel_type_features) / 1000;
683                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
684                 actual_fee = channel_value - actual_fee;
685                 assert_eq!(total_fee, actual_fee);
686         }
687
688         {
689                 // Increment the feerate by a small constant, accounting for rounding errors
690                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
691                 *feerate_lock += 4;
692         }
693         nodes[0].node.timer_tick_occurred();
694         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
695         check_added_monitors!(nodes[0], 0);
696
697         const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
698
699         // Get the TestChannelSigner for each channel, which will be used to (1) get the keys
700         // needed to sign the new commitment tx and (2) sign the new commitment tx.
701         let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
702                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
703                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
704                 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
705                 let chan_signer = local_chan.get_signer();
706                 let pubkeys = chan_signer.as_ref().pubkeys();
707                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
708                  pubkeys.funding_pubkey)
709         };
710         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
711                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
712                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
713                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
714                 let chan_signer = remote_chan.get_signer();
715                 let pubkeys = chan_signer.as_ref().pubkeys();
716                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
717                  chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
718                  pubkeys.funding_pubkey)
719         };
720
721         // Assemble the set of keys we can use for signatures for our commitment_signed message.
722         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
723                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
724
725         let res = {
726                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
727                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
728                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
729                 let local_chan_signer = local_chan.get_signer();
730                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
731                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
732                         INITIAL_COMMITMENT_NUMBER - 1,
733                         push_sats,
734                         channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, &channel_type_features) / 1000,
735                         local_funding, remote_funding,
736                         commit_tx_keys.clone(),
737                         non_buffer_feerate + 4,
738                         &mut htlcs,
739                         &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
740                 );
741                 local_chan_signer.as_ecdsa().unwrap().sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
742         };
743
744         let commit_signed_msg = msgs::CommitmentSigned {
745                 channel_id: chan.2,
746                 signature: res.0,
747                 htlc_signatures: res.1,
748                 #[cfg(taproot)]
749                 partial_signature_with_nonce: None,
750         };
751
752         let update_fee = msgs::UpdateFee {
753                 channel_id: chan.2,
754                 feerate_per_kw: non_buffer_feerate + 4,
755         };
756
757         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
758
759         //While producing the commitment_signed response after handling a received update_fee request the
760         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
761         //Should produce and error.
762         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
763         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
764         check_added_monitors!(nodes[1], 1);
765         check_closed_broadcast!(nodes[1], true);
766         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") },
767                 [nodes[0].node.get_our_node_id()], channel_value);
768 }
769
770 #[test]
771 fn test_update_fee_with_fundee_update_add_htlc() {
772         let chanmon_cfgs = create_chanmon_cfgs(2);
773         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
774         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
775         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
776         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
777
778         // balancing
779         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
780
781         {
782                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
783                 *feerate_lock += 20;
784         }
785         nodes[0].node.timer_tick_occurred();
786         check_added_monitors!(nodes[0], 1);
787
788         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
789         assert_eq!(events_0.len(), 1);
790         let (update_msg, commitment_signed) = match events_0[0] {
791                         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 } } => {
792                         (update_fee.as_ref(), commitment_signed)
793                 },
794                 _ => panic!("Unexpected event"),
795         };
796         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
797         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
798         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
799         check_added_monitors!(nodes[1], 1);
800
801         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
802
803         // nothing happens since node[1] is in AwaitingRemoteRevoke
804         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
805                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
806         {
807                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
808                 assert_eq!(added_monitors.len(), 0);
809                 added_monitors.clear();
810         }
811         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
812         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
813         // node[1] has nothing to do
814
815         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
816         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
817         check_added_monitors!(nodes[0], 1);
818
819         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
820         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
821         // No commitment_signed so get_event_msg's assert(len == 1) passes
822         check_added_monitors!(nodes[0], 1);
823         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
824         check_added_monitors!(nodes[1], 1);
825         // AwaitingRemoteRevoke ends here
826
827         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
828         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
829         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
830         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
831         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
832         assert_eq!(commitment_update.update_fee.is_none(), true);
833
834         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
835         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
836         check_added_monitors!(nodes[0], 1);
837         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
838
839         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
840         check_added_monitors!(nodes[1], 1);
841         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
842
843         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
844         check_added_monitors!(nodes[1], 1);
845         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
846         // No commitment_signed so get_event_msg's assert(len == 1) passes
847
848         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
849         check_added_monitors!(nodes[0], 1);
850         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
851
852         expect_pending_htlcs_forwardable!(nodes[0]);
853
854         let events = nodes[0].node.get_and_clear_pending_events();
855         assert_eq!(events.len(), 1);
856         match events[0] {
857                 Event::PaymentClaimable { .. } => { },
858                 _ => panic!("Unexpected event"),
859         };
860
861         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
862
863         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
864         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
865         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
866         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
867         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
868 }
869
870 #[test]
871 fn test_update_fee() {
872         let chanmon_cfgs = create_chanmon_cfgs(2);
873         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
874         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
875         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
876         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
877         let channel_id = chan.2;
878
879         // A                                        B
880         // (1) update_fee/commitment_signed      ->
881         //                                       <- (2) revoke_and_ack
882         //                                       .- send (3) commitment_signed
883         // (4) update_fee/commitment_signed      ->
884         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
885         //                                       <- (3) commitment_signed delivered
886         // send (6) revoke_and_ack               -.
887         //                                       <- (5) deliver revoke_and_ack
888         // (6) deliver revoke_and_ack            ->
889         //                                       .- send (7) commitment_signed in response to (4)
890         //                                       <- (7) deliver commitment_signed
891         // revoke_and_ack                        ->
892
893         // Create and deliver (1)...
894         let feerate;
895         {
896                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
897                 feerate = *feerate_lock;
898                 *feerate_lock = feerate + 20;
899         }
900         nodes[0].node.timer_tick_occurred();
901         check_added_monitors!(nodes[0], 1);
902
903         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
904         assert_eq!(events_0.len(), 1);
905         let (update_msg, commitment_signed) = match events_0[0] {
906                         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 } } => {
907                         (update_fee.as_ref(), commitment_signed)
908                 },
909                 _ => panic!("Unexpected event"),
910         };
911         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
912
913         // Generate (2) and (3):
914         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
915         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
916         check_added_monitors!(nodes[1], 1);
917
918         // Deliver (2):
919         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
920         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
921         check_added_monitors!(nodes[0], 1);
922
923         // Create and deliver (4)...
924         {
925                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
926                 *feerate_lock = feerate + 30;
927         }
928         nodes[0].node.timer_tick_occurred();
929         check_added_monitors!(nodes[0], 1);
930         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
931         assert_eq!(events_0.len(), 1);
932         let (update_msg, commitment_signed) = match events_0[0] {
933                         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 } } => {
934                         (update_fee.as_ref(), commitment_signed)
935                 },
936                 _ => panic!("Unexpected event"),
937         };
938
939         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
940         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
941         check_added_monitors!(nodes[1], 1);
942         // ... creating (5)
943         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
944         // No commitment_signed so get_event_msg's assert(len == 1) passes
945
946         // Handle (3), creating (6):
947         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
948         check_added_monitors!(nodes[0], 1);
949         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
950         // No commitment_signed so get_event_msg's assert(len == 1) passes
951
952         // Deliver (5):
953         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
954         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
955         check_added_monitors!(nodes[0], 1);
956
957         // Deliver (6), creating (7):
958         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
959         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
960         assert!(commitment_update.update_add_htlcs.is_empty());
961         assert!(commitment_update.update_fulfill_htlcs.is_empty());
962         assert!(commitment_update.update_fail_htlcs.is_empty());
963         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
964         assert!(commitment_update.update_fee.is_none());
965         check_added_monitors!(nodes[1], 1);
966
967         // Deliver (7)
968         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
969         check_added_monitors!(nodes[0], 1);
970         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
971         // No commitment_signed so get_event_msg's assert(len == 1) passes
972
973         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
974         check_added_monitors!(nodes[1], 1);
975         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
976
977         assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
978         assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
979         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
980         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
981         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
982 }
983
984 #[test]
985 fn fake_network_test() {
986         // Simple test which builds a network of ChannelManagers, connects them to each other, and
987         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
988         let chanmon_cfgs = create_chanmon_cfgs(4);
989         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
990         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
991         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
992
993         // Create some initial channels
994         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
995         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
996         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
997
998         // Rebalance the network a bit by relaying one payment through all the channels...
999         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1000         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1001         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1002         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1003
1004         // Send some more payments
1005         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
1006         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
1007         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
1008
1009         // Test failure packets
1010         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1011         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1012
1013         // Add a new channel that skips 3
1014         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1015
1016         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1017         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1018         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1019         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1020         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1021         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1022         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1023
1024         // Do some rebalance loop payments, simultaneously
1025         let mut hops = Vec::with_capacity(3);
1026         hops.push(RouteHop {
1027                 pubkey: nodes[2].node.get_our_node_id(),
1028                 node_features: NodeFeatures::empty(),
1029                 short_channel_id: chan_2.0.contents.short_channel_id,
1030                 channel_features: ChannelFeatures::empty(),
1031                 fee_msat: 0,
1032                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1033         });
1034         hops.push(RouteHop {
1035                 pubkey: nodes[3].node.get_our_node_id(),
1036                 node_features: NodeFeatures::empty(),
1037                 short_channel_id: chan_3.0.contents.short_channel_id,
1038                 channel_features: ChannelFeatures::empty(),
1039                 fee_msat: 0,
1040                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1041         });
1042         hops.push(RouteHop {
1043                 pubkey: nodes[1].node.get_our_node_id(),
1044                 node_features: nodes[1].node.node_features(),
1045                 short_channel_id: chan_4.0.contents.short_channel_id,
1046                 channel_features: nodes[1].node.channel_features(),
1047                 fee_msat: 1000000,
1048                 cltv_expiry_delta: TEST_FINAL_CLTV,
1049         });
1050         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;
1051         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;
1052         let payment_preimage_1 = send_along_route(&nodes[1],
1053                 Route { paths: vec![Path { hops, blinded_tail: None }], route_params: None },
1054                         &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1055
1056         let mut hops = Vec::with_capacity(3);
1057         hops.push(RouteHop {
1058                 pubkey: nodes[3].node.get_our_node_id(),
1059                 node_features: NodeFeatures::empty(),
1060                 short_channel_id: chan_4.0.contents.short_channel_id,
1061                 channel_features: ChannelFeatures::empty(),
1062                 fee_msat: 0,
1063                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1064         });
1065         hops.push(RouteHop {
1066                 pubkey: nodes[2].node.get_our_node_id(),
1067                 node_features: NodeFeatures::empty(),
1068                 short_channel_id: chan_3.0.contents.short_channel_id,
1069                 channel_features: ChannelFeatures::empty(),
1070                 fee_msat: 0,
1071                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1072         });
1073         hops.push(RouteHop {
1074                 pubkey: nodes[1].node.get_our_node_id(),
1075                 node_features: nodes[1].node.node_features(),
1076                 short_channel_id: chan_2.0.contents.short_channel_id,
1077                 channel_features: nodes[1].node.channel_features(),
1078                 fee_msat: 1000000,
1079                 cltv_expiry_delta: TEST_FINAL_CLTV,
1080         });
1081         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;
1082         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;
1083         let payment_hash_2 = send_along_route(&nodes[1],
1084                 Route { paths: vec![Path { hops, blinded_tail: None }], route_params: None },
1085                         &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1086
1087         // Claim the rebalances...
1088         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1089         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1090
1091         // Close down the channels...
1092         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1093         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1094         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
1095         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1096         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[2].node.get_our_node_id()], 100000);
1097         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1098         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1099         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure, [nodes[3].node.get_our_node_id()], 100000);
1100         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure, [nodes[2].node.get_our_node_id()], 100000);
1101         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1102         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[3].node.get_our_node_id()], 100000);
1103         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1104 }
1105
1106 #[test]
1107 fn holding_cell_htlc_counting() {
1108         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1109         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1110         // commitment dance rounds.
1111         let chanmon_cfgs = create_chanmon_cfgs(3);
1112         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1113         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1114         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1115         create_announced_chan_between_nodes(&nodes, 0, 1);
1116         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1117
1118         // Fetch a route in advance as we will be unable to once we're unable to send.
1119         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1120
1121         let mut payments = Vec::new();
1122         for _ in 0..50 {
1123                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1124                 nodes[1].node.send_payment_with_route(&route, payment_hash,
1125                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1126                 payments.push((payment_preimage, payment_hash));
1127         }
1128         check_added_monitors!(nodes[1], 1);
1129
1130         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1131         assert_eq!(events.len(), 1);
1132         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1133         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1134
1135         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1136         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1137         // another HTLC.
1138         {
1139                 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, payment_hash_1,
1140                                 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)
1141                         ), true, APIError::ChannelUnavailable { .. }, {});
1142                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1143         }
1144
1145         // This should also be true if we try to forward a payment.
1146         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1147         {
1148                 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1149                         RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1150                 check_added_monitors!(nodes[0], 1);
1151         }
1152
1153         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1154         assert_eq!(events.len(), 1);
1155         let payment_event = SendEvent::from_event(events.pop().unwrap());
1156         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1157
1158         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1159         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1160         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1161         // fails), the second will process the resulting failure and fail the HTLC backward.
1162         expect_pending_htlcs_forwardable!(nodes[1]);
1163         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 }]);
1164         check_added_monitors!(nodes[1], 1);
1165
1166         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1167         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1168         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1169
1170         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1171
1172         // Now forward all the pending HTLCs and claim them back
1173         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1174         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1175         check_added_monitors!(nodes[2], 1);
1176
1177         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1178         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1179         check_added_monitors!(nodes[1], 1);
1180         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1181
1182         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1183         check_added_monitors!(nodes[1], 1);
1184         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1185
1186         for ref update in as_updates.update_add_htlcs.iter() {
1187                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1188         }
1189         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1190         check_added_monitors!(nodes[2], 1);
1191         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1192         check_added_monitors!(nodes[2], 1);
1193         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1194
1195         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1196         check_added_monitors!(nodes[1], 1);
1197         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1198         check_added_monitors!(nodes[1], 1);
1199         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1200
1201         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1202         check_added_monitors!(nodes[2], 1);
1203
1204         expect_pending_htlcs_forwardable!(nodes[2]);
1205
1206         let events = nodes[2].node.get_and_clear_pending_events();
1207         assert_eq!(events.len(), payments.len());
1208         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1209                 match event {
1210                         &Event::PaymentClaimable { ref payment_hash, .. } => {
1211                                 assert_eq!(*payment_hash, *hash);
1212                         },
1213                         _ => panic!("Unexpected event"),
1214                 };
1215         }
1216
1217         for (preimage, _) in payments.drain(..) {
1218                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1219         }
1220
1221         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1222 }
1223
1224 #[test]
1225 fn duplicate_htlc_test() {
1226         // Test that we accept duplicate payment_hash HTLCs across the network and that
1227         // claiming/failing them are all separate and don't affect each other
1228         let chanmon_cfgs = create_chanmon_cfgs(6);
1229         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1230         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1231         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1232
1233         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1234         create_announced_chan_between_nodes(&nodes, 0, 3);
1235         create_announced_chan_between_nodes(&nodes, 1, 3);
1236         create_announced_chan_between_nodes(&nodes, 2, 3);
1237         create_announced_chan_between_nodes(&nodes, 3, 4);
1238         create_announced_chan_between_nodes(&nodes, 3, 5);
1239
1240         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1241
1242         *nodes[0].network_payment_count.borrow_mut() -= 1;
1243         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1244
1245         *nodes[0].network_payment_count.borrow_mut() -= 1;
1246         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1247
1248         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1249         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1250         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1251 }
1252
1253 #[test]
1254 fn test_duplicate_htlc_different_direction_onchain() {
1255         // Test that ChannelMonitor doesn't generate 2 preimage txn
1256         // when we have 2 HTLCs with same preimage that go across a node
1257         // in opposite directions, even with the same payment secret.
1258         let chanmon_cfgs = create_chanmon_cfgs(2);
1259         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1260         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1261         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1262
1263         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1264
1265         // balancing
1266         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1267
1268         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1269
1270         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1271         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1272         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1273
1274         // Provide preimage to node 0 by claiming payment
1275         nodes[0].node.claim_funds(payment_preimage);
1276         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1277         check_added_monitors!(nodes[0], 1);
1278
1279         // Broadcast node 1 commitment txn
1280         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1281
1282         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1283         let mut has_both_htlcs = 0; // check htlcs match ones committed
1284         for outp in remote_txn[0].output.iter() {
1285                 if outp.value == 800_000 / 1000 {
1286                         has_both_htlcs += 1;
1287                 } else if outp.value == 900_000 / 1000 {
1288                         has_both_htlcs += 1;
1289                 }
1290         }
1291         assert_eq!(has_both_htlcs, 2);
1292
1293         mine_transaction(&nodes[0], &remote_txn[0]);
1294         check_added_monitors!(nodes[0], 1);
1295         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
1296         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
1297
1298         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1299         assert_eq!(claim_txn.len(), 3);
1300
1301         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1302         check_spends!(claim_txn[1], remote_txn[0]);
1303         check_spends!(claim_txn[2], remote_txn[0]);
1304         let preimage_tx = &claim_txn[0];
1305         let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1306                 (&claim_txn[1], &claim_txn[2])
1307         } else {
1308                 (&claim_txn[2], &claim_txn[1])
1309         };
1310
1311         assert_eq!(preimage_tx.input.len(), 1);
1312         assert_eq!(preimage_bump_tx.input.len(), 1);
1313
1314         assert_eq!(preimage_tx.input.len(), 1);
1315         assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1316         assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1317
1318         assert_eq!(timeout_tx.input.len(), 1);
1319         assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1320         check_spends!(timeout_tx, remote_txn[0]);
1321         assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1322
1323         let events = nodes[0].node.get_and_clear_pending_msg_events();
1324         assert_eq!(events.len(), 3);
1325         for e in events {
1326                 match e {
1327                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1328                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1329                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1330                                 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1331                         },
1332                         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, .. } } => {
1333                                 assert!(update_add_htlcs.is_empty());
1334                                 assert!(update_fail_htlcs.is_empty());
1335                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1336                                 assert!(update_fail_malformed_htlcs.is_empty());
1337                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1338                         },
1339                         _ => panic!("Unexpected event"),
1340                 }
1341         }
1342 }
1343
1344 #[test]
1345 fn test_basic_channel_reserve() {
1346         let chanmon_cfgs = create_chanmon_cfgs(2);
1347         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1348         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1349         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1350         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1351
1352         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1353         let channel_reserve = chan_stat.channel_reserve_msat;
1354
1355         // The 2* and +1 are for the fee spike reserve.
1356         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], nodes[1], chan.2), 1 + 1, &get_channel_type_features!(nodes[0], nodes[1], chan.2));
1357         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1358         let (mut route, our_payment_hash, _, our_payment_secret) =
1359                 get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
1360         route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1361         let err = nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1362                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1363         match err {
1364                 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1365                         if let &APIError::ChannelUnavailable { .. } = &fails[0] {}
1366                         else { panic!("Unexpected error variant"); }
1367                 },
1368                 _ => panic!("Unexpected error variant"),
1369         }
1370         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1371
1372         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1373 }
1374
1375 #[test]
1376 fn test_fee_spike_violation_fails_htlc() {
1377         let chanmon_cfgs = create_chanmon_cfgs(2);
1378         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1379         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1380         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1381         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1382
1383         let (mut route, payment_hash, _, payment_secret) =
1384                 get_route_and_payment_hash!(nodes[0], nodes[1], 3460000);
1385         route.paths[0].hops[0].fee_msat += 1;
1386         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1387         let secp_ctx = Secp256k1::new();
1388         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1389
1390         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1391
1392         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1393         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1394                 3460001, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1395         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1396         let msg = msgs::UpdateAddHTLC {
1397                 channel_id: chan.2,
1398                 htlc_id: 0,
1399                 amount_msat: htlc_msat,
1400                 payment_hash: payment_hash,
1401                 cltv_expiry: htlc_cltv,
1402                 onion_routing_packet: onion_packet,
1403                 skimmed_fee_msat: None,
1404         };
1405
1406         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1407
1408         // Now manually create the commitment_signed message corresponding to the update_add
1409         // nodes[0] just sent. In the code for construction of this message, "local" refers
1410         // to the sender of the message, and "remote" refers to the receiver.
1411
1412         let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1413
1414         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1415
1416         // Get the TestChannelSigner for each channel, which will be used to (1) get the keys
1417         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1418         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1419                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1420                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1421                 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1422                 let chan_signer = local_chan.get_signer();
1423                 // Make the signer believe we validated another commitment, so we can release the secret
1424                 chan_signer.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
1425
1426                 let pubkeys = chan_signer.as_ref().pubkeys();
1427                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1428                  chan_signer.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1429                  chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1430                  chan_signer.as_ref().pubkeys().funding_pubkey)
1431         };
1432         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1433                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1434                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1435                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1436                 let chan_signer = remote_chan.get_signer();
1437                 let pubkeys = chan_signer.as_ref().pubkeys();
1438                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1439                  chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1440                  chan_signer.as_ref().pubkeys().funding_pubkey)
1441         };
1442
1443         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1444         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1445                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1446
1447         // Build the remote commitment transaction so we can sign it, and then later use the
1448         // signature for the commitment_signed message.
1449         let local_chan_balance = 1313;
1450
1451         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1452                 offered: false,
1453                 amount_msat: 3460001,
1454                 cltv_expiry: htlc_cltv,
1455                 payment_hash,
1456                 transaction_output_index: Some(1),
1457         };
1458
1459         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1460
1461         let res = {
1462                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1463                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1464                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
1465                 let local_chan_signer = local_chan.get_signer();
1466                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1467                         commitment_number,
1468                         95000,
1469                         local_chan_balance,
1470                         local_funding, remote_funding,
1471                         commit_tx_keys.clone(),
1472                         feerate_per_kw,
1473                         &mut vec![(accepted_htlc_info, ())],
1474                         &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
1475                 );
1476                 local_chan_signer.as_ecdsa().unwrap().sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1477         };
1478
1479         let commit_signed_msg = msgs::CommitmentSigned {
1480                 channel_id: chan.2,
1481                 signature: res.0,
1482                 htlc_signatures: res.1,
1483                 #[cfg(taproot)]
1484                 partial_signature_with_nonce: None,
1485         };
1486
1487         // Send the commitment_signed message to the nodes[1].
1488         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1489         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1490
1491         // Send the RAA to nodes[1].
1492         let raa_msg = msgs::RevokeAndACK {
1493                 channel_id: chan.2,
1494                 per_commitment_secret: local_secret,
1495                 next_per_commitment_point: next_local_point,
1496                 #[cfg(taproot)]
1497                 next_local_nonce: None,
1498         };
1499         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1500
1501         let events = nodes[1].node.get_and_clear_pending_msg_events();
1502         assert_eq!(events.len(), 1);
1503         // Make sure the HTLC failed in the way we expect.
1504         match events[0] {
1505                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1506                         assert_eq!(update_fail_htlcs.len(), 1);
1507                         update_fail_htlcs[0].clone()
1508                 },
1509                 _ => panic!("Unexpected event"),
1510         };
1511         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1512                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", raa_msg.channel_id), 1);
1513
1514         check_added_monitors!(nodes[1], 2);
1515 }
1516
1517 #[test]
1518 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1519         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1520         // Set the fee rate for the channel very high, to the point where the fundee
1521         // sending any above-dust amount would result in a channel reserve violation.
1522         // In this test we check that we would be prevented from sending an HTLC in
1523         // this situation.
1524         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1525         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1526         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1527         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1528         let default_config = UserConfig::default();
1529         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1530
1531         let mut push_amt = 100_000_000;
1532         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1533
1534         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1535
1536         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1537
1538         // Fetch a route in advance as we will be unable to once we're unable to send.
1539         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1540         // Sending exactly enough to hit the reserve amount should be accepted
1541         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1542                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1543         }
1544
1545         // However one more HTLC should be significantly over the reserve amount and fail.
1546         unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1547                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1548                 ), true, APIError::ChannelUnavailable { .. }, {});
1549         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1550 }
1551
1552 #[test]
1553 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1554         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1555         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1556         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1557         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1558         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1559         let default_config = UserConfig::default();
1560         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1561
1562         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1563         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1564         // transaction fee with 0 HTLCs (183 sats)).
1565         let mut push_amt = 100_000_000;
1566         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1567         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1568         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1569
1570         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1571         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1572                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1573         }
1574
1575         let (mut route, payment_hash, _, payment_secret) =
1576                 get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1577         route.paths[0].hops[0].fee_msat = 700_000;
1578         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1579         let secp_ctx = Secp256k1::new();
1580         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1581         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1582         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1583         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1584                 700_000, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1585         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1586         let msg = msgs::UpdateAddHTLC {
1587                 channel_id: chan.2,
1588                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1589                 amount_msat: htlc_msat,
1590                 payment_hash: payment_hash,
1591                 cltv_expiry: htlc_cltv,
1592                 onion_routing_packet: onion_packet,
1593                 skimmed_fee_msat: None,
1594         };
1595
1596         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1597         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1598         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);
1599         assert_eq!(nodes[0].node.list_channels().len(), 0);
1600         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1601         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1602         check_added_monitors!(nodes[0], 1);
1603         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() },
1604                 [nodes[1].node.get_our_node_id()], 100000);
1605 }
1606
1607 #[test]
1608 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1609         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1610         // calculating our commitment transaction fee (this was previously broken).
1611         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1612         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1613
1614         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1615         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1616         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1617         let default_config = UserConfig::default();
1618         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1619
1620         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1621         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1622         // transaction fee with 0 HTLCs (183 sats)).
1623         let mut push_amt = 100_000_000;
1624         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1625         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1626         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1627
1628         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1629                 + feerate_per_kw as u64 * htlc_success_tx_weight(&channel_type_features) / 1000 * 1000 - 1;
1630         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1631         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1632         // commitment transaction fee.
1633         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1634
1635         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1636         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1637                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1638         }
1639
1640         // One more than the dust amt should fail, however.
1641         let (mut route, our_payment_hash, _, our_payment_secret) =
1642                 get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt);
1643         route.paths[0].hops[0].fee_msat += 1;
1644         unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1645                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1646                 ), true, APIError::ChannelUnavailable { .. }, {});
1647 }
1648
1649 #[test]
1650 fn test_chan_init_feerate_unaffordability() {
1651         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1652         // channel reserve and feerate requirements.
1653         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1654         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1655         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1656         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1657         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1658         let default_config = UserConfig::default();
1659         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1660
1661         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1662         // HTLC.
1663         let mut push_amt = 100_000_000;
1664         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1665         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1666                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1667
1668         // During open, we don't have a "counterparty channel reserve" to check against, so that
1669         // requirement only comes into play on the open_channel handling side.
1670         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1671         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1672         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1673         open_channel_msg.push_msat += 1;
1674         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1675
1676         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1677         assert_eq!(msg_events.len(), 1);
1678         match msg_events[0] {
1679                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1680                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1681                 },
1682                 _ => panic!("Unexpected event"),
1683         }
1684 }
1685
1686 #[test]
1687 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1688         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1689         // calculating our counterparty's commitment transaction fee (this was previously broken).
1690         let chanmon_cfgs = create_chanmon_cfgs(2);
1691         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1692         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1693         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1694         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1695
1696         let payment_amt = 46000; // Dust amount
1697         // In the previous code, these first four payments would succeed.
1698         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1699         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1700         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1701         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1702
1703         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1704         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1705         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1706         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1707         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1708         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1709
1710         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1711         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1712         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1713         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1714 }
1715
1716 #[test]
1717 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1718         let chanmon_cfgs = create_chanmon_cfgs(3);
1719         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1720         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1721         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1722         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1723         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1724
1725         let feemsat = 239;
1726         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1727         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1728         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1729         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
1730
1731         // Add a 2* and +1 for the fee spike reserve.
1732         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1733         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;
1734         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1735
1736         // Add a pending HTLC.
1737         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1738         let payment_event_1 = {
1739                 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1740                         RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1741                 check_added_monitors!(nodes[0], 1);
1742
1743                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1744                 assert_eq!(events.len(), 1);
1745                 SendEvent::from_event(events.remove(0))
1746         };
1747         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1748
1749         // Attempt to trigger a channel reserve violation --> payment failure.
1750         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, &channel_type_features);
1751         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;
1752         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1753         let mut route_2 = route_1.clone();
1754         route_2.paths[0].hops.last_mut().unwrap().fee_msat = amt_msat_2;
1755
1756         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1757         let secp_ctx = Secp256k1::new();
1758         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1759         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1760         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1761         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
1762                 &route_2.paths[0], recv_value_2, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
1763         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1).unwrap();
1764         let msg = msgs::UpdateAddHTLC {
1765                 channel_id: chan.2,
1766                 htlc_id: 1,
1767                 amount_msat: htlc_msat + 1,
1768                 payment_hash: our_payment_hash_1,
1769                 cltv_expiry: htlc_cltv,
1770                 onion_routing_packet: onion_packet,
1771                 skimmed_fee_msat: None,
1772         };
1773
1774         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1775         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1776         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1777         assert_eq!(nodes[1].node.list_channels().len(), 1);
1778         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1779         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1780         check_added_monitors!(nodes[1], 1);
1781         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() },
1782                 [nodes[0].node.get_our_node_id()], 100000);
1783 }
1784
1785 #[test]
1786 fn test_inbound_outbound_capacity_is_not_zero() {
1787         let chanmon_cfgs = create_chanmon_cfgs(2);
1788         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1789         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1790         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1791         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1792         let channels0 = node_chanmgrs[0].list_channels();
1793         let channels1 = node_chanmgrs[1].list_channels();
1794         let default_config = UserConfig::default();
1795         assert_eq!(channels0.len(), 1);
1796         assert_eq!(channels1.len(), 1);
1797
1798         let reserve = get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1799         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1800         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1801
1802         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1803         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1804 }
1805
1806 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, channel_type_features: &ChannelTypeFeatures) -> u64 {
1807         (commitment_tx_base_weight(channel_type_features) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1808 }
1809
1810 #[test]
1811 fn test_channel_reserve_holding_cell_htlcs() {
1812         let chanmon_cfgs = create_chanmon_cfgs(3);
1813         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1814         // When this test was written, the default base fee floated based on the HTLC count.
1815         // It is now fixed, so we simply set the fee to the expected value here.
1816         let mut config = test_default_channel_config();
1817         config.channel_config.forwarding_fee_base_msat = 239;
1818         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1819         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1820         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1821         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1822
1823         let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1824         let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1825
1826         let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1827         let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1828
1829         macro_rules! expect_forward {
1830                 ($node: expr) => {{
1831                         let mut events = $node.node.get_and_clear_pending_msg_events();
1832                         assert_eq!(events.len(), 1);
1833                         check_added_monitors!($node, 1);
1834                         let payment_event = SendEvent::from_event(events.remove(0));
1835                         payment_event
1836                 }}
1837         }
1838
1839         let feemsat = 239; // set above
1840         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1841         let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1842         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_1.2);
1843
1844         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1845
1846         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1847         {
1848                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1849                         .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1850                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0);
1851                 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1852                 assert!(route.paths[0].hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1853
1854                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1855                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1856                         ), true, APIError::ChannelUnavailable { .. }, {});
1857                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1858         }
1859
1860         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1861         // nodes[0]'s wealth
1862         loop {
1863                 let amt_msat = recv_value_0 + total_fee_msat;
1864                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1865                 // Also, ensure that each payment has enough to be over the dust limit to
1866                 // ensure it'll be included in each commit tx fee calculation.
1867                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1868                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1869                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1870                         break;
1871                 }
1872
1873                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1874                         .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1875                 let route = get_route!(nodes[0], payment_params, recv_value_0).unwrap();
1876                 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1877                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1878
1879                 let (stat01_, stat11_, stat12_, stat22_) = (
1880                         get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1881                         get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1882                         get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1883                         get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1884                 );
1885
1886                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1887                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1888                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1889                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1890                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1891         }
1892
1893         // adding pending output.
1894         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1895         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1896         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1897         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1898         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1899         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1900         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1901         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1902         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1903         // policy.
1904         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1905         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1906         let amt_msat_1 = recv_value_1 + total_fee_msat;
1907
1908         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);
1909         let payment_event_1 = {
1910                 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1911                         RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1912                 check_added_monitors!(nodes[0], 1);
1913
1914                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1915                 assert_eq!(events.len(), 1);
1916                 SendEvent::from_event(events.remove(0))
1917         };
1918         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1919
1920         // channel reserve test with htlc pending output > 0
1921         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1922         {
1923                 let mut route = route_1.clone();
1924                 route.paths[0].hops.last_mut().unwrap().fee_msat = recv_value_2 + 1;
1925                 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
1926                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1927                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1928                         ), true, APIError::ChannelUnavailable { .. }, {});
1929                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1930         }
1931
1932         // split the rest to test holding cell
1933         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1934         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1935         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1936         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1937         {
1938                 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1939                 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);
1940         }
1941
1942         // now see if they go through on both sides
1943         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);
1944         // but this will stuck in the holding cell
1945         nodes[0].node.send_payment_with_route(&route_21, our_payment_hash_21,
1946                 RecipientOnionFields::secret_only(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1947         check_added_monitors!(nodes[0], 0);
1948         let events = nodes[0].node.get_and_clear_pending_events();
1949         assert_eq!(events.len(), 0);
1950
1951         // test with outbound holding cell amount > 0
1952         {
1953                 let (mut route, our_payment_hash, _, our_payment_secret) =
1954                         get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1955                 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1956                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1957                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1958                         ), true, APIError::ChannelUnavailable { .. }, {});
1959                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1960         }
1961
1962         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);
1963         // this will also stuck in the holding cell
1964         nodes[0].node.send_payment_with_route(&route_22, our_payment_hash_22,
1965                 RecipientOnionFields::secret_only(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1966         check_added_monitors!(nodes[0], 0);
1967         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1968         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1969
1970         // flush the pending htlc
1971         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1972         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1973         check_added_monitors!(nodes[1], 1);
1974
1975         // the pending htlc should be promoted to committed
1976         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1977         check_added_monitors!(nodes[0], 1);
1978         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1979
1980         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1981         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1982         // No commitment_signed so get_event_msg's assert(len == 1) passes
1983         check_added_monitors!(nodes[0], 1);
1984
1985         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1986         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1987         check_added_monitors!(nodes[1], 1);
1988
1989         expect_pending_htlcs_forwardable!(nodes[1]);
1990
1991         let ref payment_event_11 = expect_forward!(nodes[1]);
1992         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1993         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1994
1995         expect_pending_htlcs_forwardable!(nodes[2]);
1996         expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1997
1998         // flush the htlcs in the holding cell
1999         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2000         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2001         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2002         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2003         expect_pending_htlcs_forwardable!(nodes[1]);
2004
2005         let ref payment_event_3 = expect_forward!(nodes[1]);
2006         assert_eq!(payment_event_3.msgs.len(), 2);
2007         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2008         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2009
2010         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2011         expect_pending_htlcs_forwardable!(nodes[2]);
2012
2013         let events = nodes[2].node.get_and_clear_pending_events();
2014         assert_eq!(events.len(), 2);
2015         match events[0] {
2016                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2017                         assert_eq!(our_payment_hash_21, *payment_hash);
2018                         assert_eq!(recv_value_21, 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_21, *payment_secret);
2025                                 },
2026                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2027                         }
2028                 },
2029                 _ => panic!("Unexpected event"),
2030         }
2031         match events[1] {
2032                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2033                         assert_eq!(our_payment_hash_22, *payment_hash);
2034                         assert_eq!(recv_value_22, amount_msat);
2035                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2036                         assert_eq!(via_channel_id, Some(chan_2.2));
2037                         match &purpose {
2038                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2039                                         assert!(payment_preimage.is_none());
2040                                         assert_eq!(our_payment_secret_22, *payment_secret);
2041                                 },
2042                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2043                         }
2044                 },
2045                 _ => panic!("Unexpected event"),
2046         }
2047
2048         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2049         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2050         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2051
2052         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, &channel_type_features);
2053         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2054         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2055
2056         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
2057         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);
2058         let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2059         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2060         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2061
2062         let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2063         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2064 }
2065
2066 #[test]
2067 fn channel_reserve_in_flight_removes() {
2068         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2069         // can send to its counterparty, but due to update ordering, the other side may not yet have
2070         // considered those HTLCs fully removed.
2071         // This tests that we don't count HTLCs which will not be included in the next remote
2072         // commitment transaction towards the reserve value (as it implies no commitment transaction
2073         // will be generated which violates the remote reserve value).
2074         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2075         // To test this we:
2076         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2077         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2078         //    you only consider the value of the first HTLC, it may not),
2079         //  * start routing a third HTLC from A to B,
2080         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2081         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2082         //  * deliver the first fulfill from B
2083         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2084         //    claim,
2085         //  * deliver A's response CS and RAA.
2086         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2087         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2088         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2089         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2090         let chanmon_cfgs = create_chanmon_cfgs(2);
2091         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2092         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2093         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2094         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2095
2096         let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2097         // Route the first two HTLCs.
2098         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2099         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2100         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2101
2102         // Start routing the third HTLC (this is just used to get everyone in the right state).
2103         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2104         let send_1 = {
2105                 nodes[0].node.send_payment_with_route(&route, payment_hash_3,
2106                         RecipientOnionFields::secret_only(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2107                 check_added_monitors!(nodes[0], 1);
2108                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2109                 assert_eq!(events.len(), 1);
2110                 SendEvent::from_event(events.remove(0))
2111         };
2112
2113         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2114         // initial fulfill/CS.
2115         nodes[1].node.claim_funds(payment_preimage_1);
2116         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2117         check_added_monitors!(nodes[1], 1);
2118         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2119
2120         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2121         // remove the second HTLC when we send the HTLC back from B to A.
2122         nodes[1].node.claim_funds(payment_preimage_2);
2123         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2124         check_added_monitors!(nodes[1], 1);
2125         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2126
2127         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2128         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2129         check_added_monitors!(nodes[0], 1);
2130         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2131         expect_payment_sent(&nodes[0], payment_preimage_1, None, false, false);
2132
2133         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2134         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2135         check_added_monitors!(nodes[1], 1);
2136         // B is already AwaitingRAA, so cant generate a CS here
2137         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2138
2139         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2140         check_added_monitors!(nodes[1], 1);
2141         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2142
2143         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2144         check_added_monitors!(nodes[0], 1);
2145         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2146
2147         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2148         check_added_monitors!(nodes[1], 1);
2149         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2150
2151         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2152         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2153         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2154         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2155         // on-chain as necessary).
2156         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2157         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2158         check_added_monitors!(nodes[0], 1);
2159         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2160         expect_payment_sent(&nodes[0], payment_preimage_2, None, false, false);
2161
2162         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2163         check_added_monitors!(nodes[1], 1);
2164         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2165
2166         expect_pending_htlcs_forwardable!(nodes[1]);
2167         expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2168
2169         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2170         // resolve the second HTLC from A's point of view.
2171         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2172         check_added_monitors!(nodes[0], 1);
2173         expect_payment_path_successful!(nodes[0]);
2174         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2175
2176         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2177         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2178         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2179         let send_2 = {
2180                 nodes[1].node.send_payment_with_route(&route, payment_hash_4,
2181                         RecipientOnionFields::secret_only(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2182                 check_added_monitors!(nodes[1], 1);
2183                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2184                 assert_eq!(events.len(), 1);
2185                 SendEvent::from_event(events.remove(0))
2186         };
2187
2188         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2189         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2190         check_added_monitors!(nodes[0], 1);
2191         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2192
2193         // Now just resolve all the outstanding messages/HTLCs for completeness...
2194
2195         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2196         check_added_monitors!(nodes[1], 1);
2197         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2198
2199         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2200         check_added_monitors!(nodes[1], 1);
2201
2202         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2203         check_added_monitors!(nodes[0], 1);
2204         expect_payment_path_successful!(nodes[0]);
2205         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2206
2207         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2208         check_added_monitors!(nodes[1], 1);
2209         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2210
2211         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2212         check_added_monitors!(nodes[0], 1);
2213
2214         expect_pending_htlcs_forwardable!(nodes[0]);
2215         expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2216
2217         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2218         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2219 }
2220
2221 #[test]
2222 fn channel_monitor_network_test() {
2223         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2224         // tests that ChannelMonitor is able to recover from various states.
2225         let chanmon_cfgs = create_chanmon_cfgs(5);
2226         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2227         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2228         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2229
2230         // Create some initial channels
2231         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2232         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2233         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2234         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2235
2236         // Make sure all nodes are at the same starting height
2237         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2238         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2239         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2240         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2241         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2242
2243         // Rebalance the network a bit by relaying one payment through all the channels...
2244         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2245         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2246         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2247         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2248
2249         // Simple case with no pending HTLCs:
2250         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2251         check_added_monitors!(nodes[1], 1);
2252         check_closed_broadcast!(nodes[1], true);
2253         {
2254                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2255                 assert_eq!(node_txn.len(), 1);
2256                 mine_transaction(&nodes[0], &node_txn[0]);
2257                 check_added_monitors!(nodes[0], 1);
2258                 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2259         }
2260         check_closed_broadcast!(nodes[0], true);
2261         assert_eq!(nodes[0].node.list_channels().len(), 0);
2262         assert_eq!(nodes[1].node.list_channels().len(), 1);
2263         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2264         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
2265
2266         // One pending HTLC is discarded by the force-close:
2267         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2268
2269         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2270         // broadcasted until we reach the timelock time).
2271         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2272         check_closed_broadcast!(nodes[1], true);
2273         check_added_monitors!(nodes[1], 1);
2274         {
2275                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2276                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2277                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2278                 mine_transaction(&nodes[2], &node_txn[0]);
2279                 check_added_monitors!(nodes[2], 1);
2280                 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2281         }
2282         check_closed_broadcast!(nodes[2], true);
2283         assert_eq!(nodes[1].node.list_channels().len(), 0);
2284         assert_eq!(nodes[2].node.list_channels().len(), 1);
2285         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
2286         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2287
2288         macro_rules! claim_funds {
2289                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2290                         {
2291                                 $node.node.claim_funds($preimage);
2292                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2293                                 check_added_monitors!($node, 1);
2294
2295                                 let events = $node.node.get_and_clear_pending_msg_events();
2296                                 assert_eq!(events.len(), 1);
2297                                 match events[0] {
2298                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2299                                                 assert!(update_add_htlcs.is_empty());
2300                                                 assert!(update_fail_htlcs.is_empty());
2301                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2302                                         },
2303                                         _ => panic!("Unexpected event"),
2304                                 };
2305                         }
2306                 }
2307         }
2308
2309         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2310         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2311         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2312         check_added_monitors!(nodes[2], 1);
2313         check_closed_broadcast!(nodes[2], true);
2314         let node2_commitment_txid;
2315         {
2316                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2317                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2318                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2319                 node2_commitment_txid = node_txn[0].txid();
2320
2321                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2322                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2323                 mine_transaction(&nodes[3], &node_txn[0]);
2324                 check_added_monitors!(nodes[3], 1);
2325                 check_preimage_claim(&nodes[3], &node_txn);
2326         }
2327         check_closed_broadcast!(nodes[3], true);
2328         assert_eq!(nodes[2].node.list_channels().len(), 0);
2329         assert_eq!(nodes[3].node.list_channels().len(), 1);
2330         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed, [nodes[3].node.get_our_node_id()], 100000);
2331         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
2332
2333         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2334         // confusing us in the following tests.
2335         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2336
2337         // One pending HTLC to time out:
2338         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2339         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2340         // buffer space).
2341
2342         let (close_chan_update_1, close_chan_update_2) = {
2343                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2344                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2345                 assert_eq!(events.len(), 2);
2346                 let close_chan_update_1 = match events[0] {
2347                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2348                                 msg.clone()
2349                         },
2350                         _ => panic!("Unexpected event"),
2351                 };
2352                 match events[1] {
2353                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2354                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2355                         },
2356                         _ => panic!("Unexpected event"),
2357                 }
2358                 check_added_monitors!(nodes[3], 1);
2359
2360                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2361                 {
2362                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2363                         node_txn.retain(|tx| {
2364                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2365                                         false
2366                                 } else { true }
2367                         });
2368                 }
2369
2370                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2371
2372                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2373                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2374
2375                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2376                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2377                 assert_eq!(events.len(), 2);
2378                 let close_chan_update_2 = match events[0] {
2379                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2380                                 msg.clone()
2381                         },
2382                         _ => panic!("Unexpected event"),
2383                 };
2384                 match events[1] {
2385                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2386                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2387                         },
2388                         _ => panic!("Unexpected event"),
2389                 }
2390                 check_added_monitors!(nodes[4], 1);
2391                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2392
2393                 mine_transaction(&nodes[4], &node_txn[0]);
2394                 check_preimage_claim(&nodes[4], &node_txn);
2395                 (close_chan_update_1, close_chan_update_2)
2396         };
2397         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2398         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2399         assert_eq!(nodes[3].node.list_channels().len(), 0);
2400         assert_eq!(nodes[4].node.list_channels().len(), 0);
2401
2402         assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2403                 ChannelMonitorUpdateStatus::Completed);
2404         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed, [nodes[4].node.get_our_node_id()], 100000);
2405         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed, [nodes[3].node.get_our_node_id()], 100000);
2406 }
2407
2408 #[test]
2409 fn test_justice_tx_htlc_timeout() {
2410         // Test justice txn built on revoked HTLC-Timeout tx, against both sides
2411         let mut alice_config = UserConfig::default();
2412         alice_config.channel_handshake_config.announced_channel = true;
2413         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2414         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2415         let mut bob_config = UserConfig::default();
2416         bob_config.channel_handshake_config.announced_channel = true;
2417         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2418         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2419         let user_cfgs = [Some(alice_config), Some(bob_config)];
2420         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2421         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2422         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2423         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2424         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2425         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2426         // Create some new channels:
2427         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2428
2429         // A pending HTLC which will be revoked:
2430         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2431         // Get the will-be-revoked local txn from nodes[0]
2432         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2433         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2434         assert_eq!(revoked_local_txn[0].input.len(), 1);
2435         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2436         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2437         assert_eq!(revoked_local_txn[1].input.len(), 1);
2438         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2439         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2440         // Revoke the old state
2441         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2442
2443         {
2444                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2445                 {
2446                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2447                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2448                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2449                         check_spends!(node_txn[0], revoked_local_txn[0]);
2450                         node_txn.swap_remove(0);
2451                 }
2452                 check_added_monitors!(nodes[1], 1);
2453                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2454                 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2455
2456                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2457                 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2458                 // Verify broadcast of revoked HTLC-timeout
2459                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2460                 check_added_monitors!(nodes[0], 1);
2461                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2462                 // Broadcast revoked HTLC-timeout on node 1
2463                 mine_transaction(&nodes[1], &node_txn[1]);
2464                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2465         }
2466         get_announce_close_broadcast_events(&nodes, 0, 1);
2467         assert_eq!(nodes[0].node.list_channels().len(), 0);
2468         assert_eq!(nodes[1].node.list_channels().len(), 0);
2469 }
2470
2471 #[test]
2472 fn test_justice_tx_htlc_success() {
2473         // Test justice txn built on revoked HTLC-Success tx, against both sides
2474         let mut alice_config = UserConfig::default();
2475         alice_config.channel_handshake_config.announced_channel = true;
2476         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2477         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2478         let mut bob_config = UserConfig::default();
2479         bob_config.channel_handshake_config.announced_channel = true;
2480         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2481         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2482         let user_cfgs = [Some(alice_config), Some(bob_config)];
2483         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2484         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2485         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2486         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2487         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2488         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2489         // Create some new channels:
2490         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2491
2492         // A pending HTLC which will be revoked:
2493         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2494         // Get the will-be-revoked local txn from B
2495         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2496         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2497         assert_eq!(revoked_local_txn[0].input.len(), 1);
2498         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2499         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2500         // Revoke the old state
2501         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2502         {
2503                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2504                 {
2505                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2506                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2507                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2508
2509                         check_spends!(node_txn[0], revoked_local_txn[0]);
2510                         node_txn.swap_remove(0);
2511                 }
2512                 check_added_monitors!(nodes[0], 1);
2513                 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2514
2515                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2516                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2517                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2518                 check_added_monitors!(nodes[1], 1);
2519                 mine_transaction(&nodes[0], &node_txn[1]);
2520                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2521                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2522         }
2523         get_announce_close_broadcast_events(&nodes, 0, 1);
2524         assert_eq!(nodes[0].node.list_channels().len(), 0);
2525         assert_eq!(nodes[1].node.list_channels().len(), 0);
2526 }
2527
2528 #[test]
2529 fn revoked_output_claim() {
2530         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2531         // transaction is broadcast by its counterparty
2532         let chanmon_cfgs = create_chanmon_cfgs(2);
2533         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2534         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2535         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2536         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2537         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2538         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2539         assert_eq!(revoked_local_txn.len(), 1);
2540         // Only output is the full channel value back to nodes[0]:
2541         assert_eq!(revoked_local_txn[0].output.len(), 1);
2542         // Send a payment through, updating everyone's latest commitment txn
2543         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2544
2545         // Inform nodes[1] that nodes[0] broadcast a stale tx
2546         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2547         check_added_monitors!(nodes[1], 1);
2548         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2549         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2550         assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2551
2552         check_spends!(node_txn[0], revoked_local_txn[0]);
2553
2554         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2555         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2556         get_announce_close_broadcast_events(&nodes, 0, 1);
2557         check_added_monitors!(nodes[0], 1);
2558         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2559 }
2560
2561 #[test]
2562 fn test_forming_justice_tx_from_monitor_updates() {
2563         do_test_forming_justice_tx_from_monitor_updates(true);
2564         do_test_forming_justice_tx_from_monitor_updates(false);
2565 }
2566
2567 fn do_test_forming_justice_tx_from_monitor_updates(broadcast_initial_commitment: bool) {
2568         // Simple test to make sure that the justice tx formed in WatchtowerPersister
2569         // is properly formed and can be broadcasted/confirmed successfully in the event
2570         // that a revoked commitment transaction is broadcasted
2571         // (Similar to `revoked_output_claim` test but we get the justice tx + broadcast manually)
2572         let chanmon_cfgs = create_chanmon_cfgs(2);
2573         let destination_script0 = chanmon_cfgs[0].keys_manager.get_destination_script().unwrap();
2574         let destination_script1 = chanmon_cfgs[1].keys_manager.get_destination_script().unwrap();
2575         let persisters = vec![WatchtowerPersister::new(destination_script0),
2576                 WatchtowerPersister::new(destination_script1)];
2577         let node_cfgs = create_node_cfgs_with_persisters(2, &chanmon_cfgs, persisters.iter().collect());
2578         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2579         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2580         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
2581         let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
2582
2583         if !broadcast_initial_commitment {
2584                 // Send a payment to move the channel forward
2585                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000);
2586         }
2587
2588         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output.
2589         // We'll keep this commitment transaction to broadcast once it's revoked.
2590         let revoked_local_txn = get_local_commitment_txn!(nodes[0], channel_id);
2591         assert_eq!(revoked_local_txn.len(), 1);
2592         let revoked_commitment_tx = &revoked_local_txn[0];
2593
2594         // Send another payment, now revoking the previous commitment tx
2595         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000);
2596
2597         let justice_tx = persisters[1].justice_tx(funding_txo, &revoked_commitment_tx.txid()).unwrap();
2598         check_spends!(justice_tx, revoked_commitment_tx);
2599
2600         mine_transactions(&nodes[1], &[revoked_commitment_tx, &justice_tx]);
2601         mine_transactions(&nodes[0], &[revoked_commitment_tx, &justice_tx]);
2602
2603         check_added_monitors!(nodes[1], 1);
2604         check_closed_event(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false,
2605                 &[nodes[0].node.get_our_node_id()], 100_000);
2606         get_announce_close_broadcast_events(&nodes, 1, 0);
2607
2608         check_added_monitors!(nodes[0], 1);
2609         check_closed_event(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false,
2610                 &[nodes[1].node.get_our_node_id()], 100_000);
2611
2612         // Check that the justice tx has sent the revoked output value to nodes[1]
2613         let monitor = get_monitor!(nodes[1], channel_id);
2614         let total_claimable_balance = monitor.get_claimable_balances().iter().fold(0, |sum, balance| {
2615                 match balance {
2616                         channelmonitor::Balance::ClaimableAwaitingConfirmations { amount_satoshis, .. } => sum + amount_satoshis,
2617                         _ => panic!("Unexpected balance type"),
2618                 }
2619         });
2620         // On the first commitment, node[1]'s balance was below dust so it didn't have an output
2621         let node1_channel_balance = if broadcast_initial_commitment { 0 } else { revoked_commitment_tx.output[0].value };
2622         let expected_claimable_balance = node1_channel_balance + justice_tx.output[0].value;
2623         assert_eq!(total_claimable_balance, expected_claimable_balance);
2624 }
2625
2626
2627 #[test]
2628 fn claim_htlc_outputs_shared_tx() {
2629         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2630         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2631         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2632         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2633         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2634         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2635
2636         // Create some new channel:
2637         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2638
2639         // Rebalance the network to generate htlc in the two directions
2640         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2641         // 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
2642         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2643         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2644
2645         // Get the will-be-revoked local txn from node[0]
2646         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2647         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2648         assert_eq!(revoked_local_txn[0].input.len(), 1);
2649         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2650         assert_eq!(revoked_local_txn[1].input.len(), 1);
2651         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2652         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2653         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2654
2655         //Revoke the old state
2656         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2657
2658         {
2659                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2660                 check_added_monitors!(nodes[0], 1);
2661                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2662                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2663                 check_added_monitors!(nodes[1], 1);
2664                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2665                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2666                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2667
2668                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2669                 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2670
2671                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2672                 check_spends!(node_txn[0], 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[0].input[1].witness.last().unwrap().len());
2677                 witness_lens.insert(node_txn[0].input[2].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 transaction and check that we get an HTLC failure after
2684                 // ANTI_REORG_DELAY confirmations.
2685                 mine_transaction(&nodes[1], &node_txn[0]);
2686                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2687                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2688         }
2689         get_announce_close_broadcast_events(&nodes, 0, 1);
2690         assert_eq!(nodes[0].node.list_channels().len(), 0);
2691         assert_eq!(nodes[1].node.list_channels().len(), 0);
2692 }
2693
2694 #[test]
2695 fn claim_htlc_outputs_single_tx() {
2696         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2697         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2698         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2699         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2700         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2701         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2702
2703         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2704
2705         // Rebalance the network to generate htlc in the two directions
2706         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2707         // 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
2708         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2709         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2710         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2711
2712         // Get the will-be-revoked local txn from node[0]
2713         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2714
2715         //Revoke the old state
2716         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2717
2718         {
2719                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2720                 check_added_monitors!(nodes[0], 1);
2721                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2722                 check_added_monitors!(nodes[1], 1);
2723                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2724                 let mut events = nodes[0].node.get_and_clear_pending_events();
2725                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2726                 match events.last().unwrap() {
2727                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2728                         _ => panic!("Unexpected event"),
2729                 }
2730
2731                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2732                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2733
2734                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcast();
2735
2736                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2737                 assert_eq!(node_txn[0].input.len(), 1);
2738                 check_spends!(node_txn[0], chan_1.3);
2739                 assert_eq!(node_txn[1].input.len(), 1);
2740                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2741                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2742                 check_spends!(node_txn[1], node_txn[0]);
2743
2744                 // Filter out any non justice transactions.
2745                 node_txn.retain(|tx| tx.input[0].previous_output.txid == revoked_local_txn[0].txid());
2746                 assert!(node_txn.len() > 3);
2747
2748                 assert_eq!(node_txn[0].input.len(), 1);
2749                 assert_eq!(node_txn[1].input.len(), 1);
2750                 assert_eq!(node_txn[2].input.len(), 1);
2751
2752                 check_spends!(node_txn[0], revoked_local_txn[0]);
2753                 check_spends!(node_txn[1], revoked_local_txn[0]);
2754                 check_spends!(node_txn[2], revoked_local_txn[0]);
2755
2756                 let mut witness_lens = BTreeSet::new();
2757                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2758                 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2759                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2760                 assert_eq!(witness_lens.len(), 3);
2761                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2762                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2763                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2764
2765                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2766                 // ANTI_REORG_DELAY confirmations.
2767                 mine_transaction(&nodes[1], &node_txn[0]);
2768                 mine_transaction(&nodes[1], &node_txn[1]);
2769                 mine_transaction(&nodes[1], &node_txn[2]);
2770                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2771                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2772         }
2773         get_announce_close_broadcast_events(&nodes, 0, 1);
2774         assert_eq!(nodes[0].node.list_channels().len(), 0);
2775         assert_eq!(nodes[1].node.list_channels().len(), 0);
2776 }
2777
2778 #[test]
2779 fn test_htlc_on_chain_success() {
2780         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2781         // the preimage backward accordingly. So here we test that ChannelManager is
2782         // broadcasting the right event to other nodes in payment path.
2783         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2784         // A --------------------> B ----------------------> C (preimage)
2785         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2786         // commitment transaction was broadcast.
2787         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2788         // towards B.
2789         // B should be able to claim via preimage if A then broadcasts its local tx.
2790         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2791         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2792         // PaymentSent event).
2793
2794         let chanmon_cfgs = create_chanmon_cfgs(3);
2795         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2796         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2797         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2798
2799         // Create some initial channels
2800         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2801         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2802
2803         // Ensure all nodes are at the same height
2804         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2805         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2806         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2807         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2808
2809         // Rebalance the network a bit by relaying one payment through all the channels...
2810         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2811         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2812
2813         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2814         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2815
2816         // Broadcast legit commitment tx from C on B's chain
2817         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2818         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2819         assert_eq!(commitment_tx.len(), 1);
2820         check_spends!(commitment_tx[0], chan_2.3);
2821         nodes[2].node.claim_funds(our_payment_preimage);
2822         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2823         nodes[2].node.claim_funds(our_payment_preimage_2);
2824         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2825         check_added_monitors!(nodes[2], 2);
2826         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2827         assert!(updates.update_add_htlcs.is_empty());
2828         assert!(updates.update_fail_htlcs.is_empty());
2829         assert!(updates.update_fail_malformed_htlcs.is_empty());
2830         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2831
2832         mine_transaction(&nodes[2], &commitment_tx[0]);
2833         check_closed_broadcast!(nodes[2], true);
2834         check_added_monitors!(nodes[2], 1);
2835         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2836         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2837         assert_eq!(node_txn.len(), 2);
2838         check_spends!(node_txn[0], commitment_tx[0]);
2839         check_spends!(node_txn[1], commitment_tx[0]);
2840         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2841         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2842         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2843         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2844         assert_eq!(node_txn[0].lock_time.0, 0);
2845         assert_eq!(node_txn[1].lock_time.0, 0);
2846
2847         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2848         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), node_txn[0].clone(), node_txn[1].clone()]));
2849         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2850         {
2851                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2852                 assert_eq!(added_monitors.len(), 1);
2853                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2854                 added_monitors.clear();
2855         }
2856         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2857         assert_eq!(forwarded_events.len(), 3);
2858         match forwarded_events[0] {
2859                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2860                 _ => panic!("Unexpected event"),
2861         }
2862         let chan_id = Some(chan_1.2);
2863         match forwarded_events[1] {
2864                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2865                         assert_eq!(fee_earned_msat, Some(1000));
2866                         assert_eq!(prev_channel_id, chan_id);
2867                         assert_eq!(claim_from_onchain_tx, true);
2868                         assert_eq!(next_channel_id, Some(chan_2.2));
2869                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2870                 },
2871                 _ => panic!()
2872         }
2873         match forwarded_events[2] {
2874                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2875                         assert_eq!(fee_earned_msat, Some(1000));
2876                         assert_eq!(prev_channel_id, chan_id);
2877                         assert_eq!(claim_from_onchain_tx, true);
2878                         assert_eq!(next_channel_id, Some(chan_2.2));
2879                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2880                 },
2881                 _ => panic!()
2882         }
2883         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2884         {
2885                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2886                 assert_eq!(added_monitors.len(), 2);
2887                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2888                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2889                 added_monitors.clear();
2890         }
2891         assert_eq!(events.len(), 3);
2892
2893         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2894         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2895
2896         match nodes_2_event {
2897                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2898                 _ => panic!("Unexpected event"),
2899         }
2900
2901         match nodes_0_event {
2902                 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, .. } } => {
2903                         assert!(update_add_htlcs.is_empty());
2904                         assert!(update_fail_htlcs.is_empty());
2905                         assert_eq!(update_fulfill_htlcs.len(), 1);
2906                         assert!(update_fail_malformed_htlcs.is_empty());
2907                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2908                 },
2909                 _ => panic!("Unexpected event"),
2910         };
2911
2912         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2913         match events[0] {
2914                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2915                 _ => panic!("Unexpected event"),
2916         }
2917
2918         macro_rules! check_tx_local_broadcast {
2919                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2920                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2921                         assert_eq!(node_txn.len(), 2);
2922                         // Node[1]: 2 * HTLC-timeout tx
2923                         // Node[0]: 2 * HTLC-timeout tx
2924                         check_spends!(node_txn[0], $commitment_tx);
2925                         check_spends!(node_txn[1], $commitment_tx);
2926                         assert_ne!(node_txn[0].lock_time.0, 0);
2927                         assert_ne!(node_txn[1].lock_time.0, 0);
2928                         if $htlc_offered {
2929                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2930                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2931                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2932                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2933                         } else {
2934                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2935                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2936                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2937                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2938                         }
2939                         node_txn.clear();
2940                 } }
2941         }
2942         // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2943         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2944
2945         // Broadcast legit commitment tx from A on B's chain
2946         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2947         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2948         check_spends!(node_a_commitment_tx[0], chan_1.3);
2949         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2950         check_closed_broadcast!(nodes[1], true);
2951         check_added_monitors!(nodes[1], 1);
2952         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2953         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2954         assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2955         let commitment_spend =
2956                 if node_txn.len() == 1 {
2957                         &node_txn[0]
2958                 } else {
2959                         // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2960                         // FullBlockViaListen
2961                         if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2962                                 check_spends!(node_txn[1], commitment_tx[0]);
2963                                 check_spends!(node_txn[2], commitment_tx[0]);
2964                                 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2965                                 &node_txn[0]
2966                         } else {
2967                                 check_spends!(node_txn[0], commitment_tx[0]);
2968                                 check_spends!(node_txn[1], commitment_tx[0]);
2969                                 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2970                                 &node_txn[2]
2971                         }
2972                 };
2973
2974         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2975         assert_eq!(commitment_spend.input.len(), 2);
2976         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2977         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2978         assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1);
2979         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2980         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2981         // we already checked the same situation with A.
2982
2983         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2984         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()]));
2985         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
2986         check_closed_broadcast!(nodes[0], true);
2987         check_added_monitors!(nodes[0], 1);
2988         let events = nodes[0].node.get_and_clear_pending_events();
2989         assert_eq!(events.len(), 5);
2990         let mut first_claimed = false;
2991         for event in events {
2992                 match event {
2993                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2994                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2995                                         assert!(!first_claimed);
2996                                         first_claimed = true;
2997                                 } else {
2998                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2999                                         assert_eq!(payment_hash, payment_hash_2);
3000                                 }
3001                         },
3002                         Event::PaymentPathSuccessful { .. } => {},
3003                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
3004                         _ => panic!("Unexpected event"),
3005                 }
3006         }
3007         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
3008 }
3009
3010 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
3011         // Test that in case of a unilateral close onchain, we detect the state of output and
3012         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
3013         // broadcasting the right event to other nodes in payment path.
3014         // A ------------------> B ----------------------> C (timeout)
3015         //    B's commitment tx                 C's commitment tx
3016         //            \                                  \
3017         //         B's HTLC timeout tx               B's timeout tx
3018
3019         let chanmon_cfgs = create_chanmon_cfgs(3);
3020         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3021         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3022         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3023         *nodes[0].connect_style.borrow_mut() = connect_style;
3024         *nodes[1].connect_style.borrow_mut() = connect_style;
3025         *nodes[2].connect_style.borrow_mut() = connect_style;
3026
3027         // Create some intial channels
3028         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
3029         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3030
3031         // Rebalance the network a bit by relaying one payment thorugh all the channels...
3032         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3033         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3034
3035         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
3036
3037         // Broadcast legit commitment tx from C on B's chain
3038         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
3039         check_spends!(commitment_tx[0], chan_2.3);
3040         nodes[2].node.fail_htlc_backwards(&payment_hash);
3041         check_added_monitors!(nodes[2], 0);
3042         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
3043         check_added_monitors!(nodes[2], 1);
3044
3045         let events = nodes[2].node.get_and_clear_pending_msg_events();
3046         assert_eq!(events.len(), 1);
3047         match events[0] {
3048                 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, .. } } => {
3049                         assert!(update_add_htlcs.is_empty());
3050                         assert!(!update_fail_htlcs.is_empty());
3051                         assert!(update_fulfill_htlcs.is_empty());
3052                         assert!(update_fail_malformed_htlcs.is_empty());
3053                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
3054                 },
3055                 _ => panic!("Unexpected event"),
3056         };
3057         mine_transaction(&nodes[2], &commitment_tx[0]);
3058         check_closed_broadcast!(nodes[2], true);
3059         check_added_monitors!(nodes[2], 1);
3060         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
3061         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
3062         assert_eq!(node_txn.len(), 0);
3063
3064         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
3065         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
3066         mine_transaction(&nodes[1], &commitment_tx[0]);
3067         check_closed_event!(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false
3068                 , [nodes[2].node.get_our_node_id()], 100000);
3069         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
3070         let timeout_tx = {
3071                 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
3072                 if nodes[1].connect_style.borrow().skips_blocks() {
3073                         assert_eq!(txn.len(), 1);
3074                 } else {
3075                         assert_eq!(txn.len(), 3); // Two extra fee bumps for timeout transaction
3076                 }
3077                 txn.iter().for_each(|tx| check_spends!(tx, commitment_tx[0]));
3078                 assert_eq!(txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3079                 txn.remove(0)
3080         };
3081
3082         mine_transaction(&nodes[1], &timeout_tx);
3083         check_added_monitors!(nodes[1], 1);
3084         check_closed_broadcast!(nodes[1], true);
3085
3086         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3087
3088         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 }]);
3089         check_added_monitors!(nodes[1], 1);
3090         let events = nodes[1].node.get_and_clear_pending_msg_events();
3091         assert_eq!(events.len(), 1);
3092         match events[0] {
3093                 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, .. } } => {
3094                         assert!(update_add_htlcs.is_empty());
3095                         assert!(!update_fail_htlcs.is_empty());
3096                         assert!(update_fulfill_htlcs.is_empty());
3097                         assert!(update_fail_malformed_htlcs.is_empty());
3098                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3099                 },
3100                 _ => panic!("Unexpected event"),
3101         };
3102
3103         // Broadcast legit commitment tx from B on A's chain
3104         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3105         check_spends!(commitment_tx[0], chan_1.3);
3106
3107         mine_transaction(&nodes[0], &commitment_tx[0]);
3108         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3109
3110         check_closed_broadcast!(nodes[0], true);
3111         check_added_monitors!(nodes[0], 1);
3112         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
3113         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
3114         assert_eq!(node_txn.len(), 1);
3115         check_spends!(node_txn[0], commitment_tx[0]);
3116         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3117 }
3118
3119 #[test]
3120 fn test_htlc_on_chain_timeout() {
3121         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3122         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3123         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3124 }
3125
3126 #[test]
3127 fn test_simple_commitment_revoked_fail_backward() {
3128         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3129         // and fail backward accordingly.
3130
3131         let chanmon_cfgs = create_chanmon_cfgs(3);
3132         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3133         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3134         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3135
3136         // Create some initial channels
3137         create_announced_chan_between_nodes(&nodes, 0, 1);
3138         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3139
3140         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3141         // Get the will-be-revoked local txn from nodes[2]
3142         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3143         // Revoke the old state
3144         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3145
3146         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3147
3148         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3149         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3150         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3151         check_added_monitors!(nodes[1], 1);
3152         check_closed_broadcast!(nodes[1], true);
3153
3154         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 }]);
3155         check_added_monitors!(nodes[1], 1);
3156         let events = nodes[1].node.get_and_clear_pending_msg_events();
3157         assert_eq!(events.len(), 1);
3158         match events[0] {
3159                 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, .. } } => {
3160                         assert!(update_add_htlcs.is_empty());
3161                         assert_eq!(update_fail_htlcs.len(), 1);
3162                         assert!(update_fulfill_htlcs.is_empty());
3163                         assert!(update_fail_malformed_htlcs.is_empty());
3164                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3165
3166                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3167                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3168                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3169                 },
3170                 _ => panic!("Unexpected event"),
3171         }
3172 }
3173
3174 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3175         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3176         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3177         // commitment transaction anymore.
3178         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3179         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3180         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3181         // technically disallowed and we should probably handle it reasonably.
3182         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3183         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3184         // transactions:
3185         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3186         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3187         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3188         //   and once they revoke the previous commitment transaction (allowing us to send a new
3189         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3190         let chanmon_cfgs = create_chanmon_cfgs(3);
3191         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3192         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3193         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3194
3195         // Create some initial channels
3196         create_announced_chan_between_nodes(&nodes, 0, 1);
3197         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3198
3199         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 });
3200         // Get the will-be-revoked local txn from nodes[2]
3201         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3202         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3203         // Revoke the old state
3204         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3205
3206         let value = if use_dust {
3207                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3208                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3209                 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3210                         .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().context.holder_dust_limit_satoshis * 1000
3211         } else { 3000000 };
3212
3213         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3214         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3215         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3216
3217         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3218         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3219         check_added_monitors!(nodes[2], 1);
3220         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3221         assert!(updates.update_add_htlcs.is_empty());
3222         assert!(updates.update_fulfill_htlcs.is_empty());
3223         assert!(updates.update_fail_malformed_htlcs.is_empty());
3224         assert_eq!(updates.update_fail_htlcs.len(), 1);
3225         assert!(updates.update_fee.is_none());
3226         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3227         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3228         // Drop the last RAA from 3 -> 2
3229
3230         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3231         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3232         check_added_monitors!(nodes[2], 1);
3233         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3234         assert!(updates.update_add_htlcs.is_empty());
3235         assert!(updates.update_fulfill_htlcs.is_empty());
3236         assert!(updates.update_fail_malformed_htlcs.is_empty());
3237         assert_eq!(updates.update_fail_htlcs.len(), 1);
3238         assert!(updates.update_fee.is_none());
3239         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3240         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3241         check_added_monitors!(nodes[1], 1);
3242         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3243         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3244         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3245         check_added_monitors!(nodes[2], 1);
3246
3247         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3248         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3249         check_added_monitors!(nodes[2], 1);
3250         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3251         assert!(updates.update_add_htlcs.is_empty());
3252         assert!(updates.update_fulfill_htlcs.is_empty());
3253         assert!(updates.update_fail_malformed_htlcs.is_empty());
3254         assert_eq!(updates.update_fail_htlcs.len(), 1);
3255         assert!(updates.update_fee.is_none());
3256         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3257         // At this point first_payment_hash has dropped out of the latest two commitment
3258         // transactions that nodes[1] is tracking...
3259         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3260         check_added_monitors!(nodes[1], 1);
3261         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3262         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3263         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3264         check_added_monitors!(nodes[2], 1);
3265
3266         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3267         // on nodes[2]'s RAA.
3268         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3269         nodes[1].node.send_payment_with_route(&route, fourth_payment_hash,
3270                 RecipientOnionFields::secret_only(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3271         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3272         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3273         check_added_monitors!(nodes[1], 0);
3274
3275         if deliver_bs_raa {
3276                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3277                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3278                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3279                 check_added_monitors!(nodes[1], 1);
3280                 let events = nodes[1].node.get_and_clear_pending_events();
3281                 assert_eq!(events.len(), 2);
3282                 match events[0] {
3283                         Event::PendingHTLCsForwardable { .. } => { },
3284                         _ => panic!("Unexpected event"),
3285                 };
3286                 match events[1] {
3287                         Event::HTLCHandlingFailed { .. } => { },
3288                         _ => panic!("Unexpected event"),
3289                 }
3290                 // Deliberately don't process the pending fail-back so they all fail back at once after
3291                 // block connection just like the !deliver_bs_raa case
3292         }
3293
3294         let mut failed_htlcs = HashSet::new();
3295         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3296
3297         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3298         check_added_monitors!(nodes[1], 1);
3299         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3300
3301         let events = nodes[1].node.get_and_clear_pending_events();
3302         assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3303         match events[0] {
3304                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3305                 _ => panic!("Unexepected event"),
3306         }
3307         match events[1] {
3308                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3309                         assert_eq!(*payment_hash, fourth_payment_hash);
3310                 },
3311                 _ => panic!("Unexpected event"),
3312         }
3313         match events[2] {
3314                 Event::PaymentFailed { ref payment_hash, .. } => {
3315                         assert_eq!(*payment_hash, fourth_payment_hash);
3316                 },
3317                 _ => panic!("Unexpected event"),
3318         }
3319
3320         nodes[1].node.process_pending_htlc_forwards();
3321         check_added_monitors!(nodes[1], 1);
3322
3323         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3324         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3325
3326         if deliver_bs_raa {
3327                 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3328                 match nodes_2_event {
3329                         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, .. } } => {
3330                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3331                                 assert_eq!(update_add_htlcs.len(), 1);
3332                                 assert!(update_fulfill_htlcs.is_empty());
3333                                 assert!(update_fail_htlcs.is_empty());
3334                                 assert!(update_fail_malformed_htlcs.is_empty());
3335                         },
3336                         _ => panic!("Unexpected event"),
3337                 }
3338         }
3339
3340         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3341         match nodes_2_event {
3342                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3343                         assert_eq!(channel_id, chan_2.2);
3344                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3345                 },
3346                 _ => panic!("Unexpected event"),
3347         }
3348
3349         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3350         match nodes_0_event {
3351                 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, .. } } => {
3352                         assert!(update_add_htlcs.is_empty());
3353                         assert_eq!(update_fail_htlcs.len(), 3);
3354                         assert!(update_fulfill_htlcs.is_empty());
3355                         assert!(update_fail_malformed_htlcs.is_empty());
3356                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3357
3358                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3359                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3360                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3361
3362                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3363
3364                         let events = nodes[0].node.get_and_clear_pending_events();
3365                         assert_eq!(events.len(), 6);
3366                         match events[0] {
3367                                 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3368                                         assert!(failed_htlcs.insert(payment_hash.0));
3369                                         // If we delivered B's RAA we got an unknown preimage error, not something
3370                                         // that we should update our routing table for.
3371                                         if !deliver_bs_raa {
3372                                                 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3373                                         }
3374                                 },
3375                                 _ => panic!("Unexpected event"),
3376                         }
3377                         match events[1] {
3378                                 Event::PaymentFailed { ref payment_hash, .. } => {
3379                                         assert_eq!(*payment_hash, first_payment_hash);
3380                                 },
3381                                 _ => panic!("Unexpected event"),
3382                         }
3383                         match events[2] {
3384                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3385                                         assert!(failed_htlcs.insert(payment_hash.0));
3386                                 },
3387                                 _ => panic!("Unexpected event"),
3388                         }
3389                         match events[3] {
3390                                 Event::PaymentFailed { ref payment_hash, .. } => {
3391                                         assert_eq!(*payment_hash, second_payment_hash);
3392                                 },
3393                                 _ => panic!("Unexpected event"),
3394                         }
3395                         match events[4] {
3396                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3397                                         assert!(failed_htlcs.insert(payment_hash.0));
3398                                 },
3399                                 _ => panic!("Unexpected event"),
3400                         }
3401                         match events[5] {
3402                                 Event::PaymentFailed { ref payment_hash, .. } => {
3403                                         assert_eq!(*payment_hash, third_payment_hash);
3404                                 },
3405                                 _ => panic!("Unexpected event"),
3406                         }
3407                 },
3408                 _ => panic!("Unexpected event"),
3409         }
3410
3411         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3412         match events[0] {
3413                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3414                 _ => panic!("Unexpected event"),
3415         }
3416
3417         assert!(failed_htlcs.contains(&first_payment_hash.0));
3418         assert!(failed_htlcs.contains(&second_payment_hash.0));
3419         assert!(failed_htlcs.contains(&third_payment_hash.0));
3420 }
3421
3422 #[test]
3423 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3424         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3425         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3426         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3427         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3428 }
3429
3430 #[test]
3431 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3432         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3433         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3434         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3435         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3436 }
3437
3438 #[test]
3439 fn fail_backward_pending_htlc_upon_channel_failure() {
3440         let chanmon_cfgs = create_chanmon_cfgs(2);
3441         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3442         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3443         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3444         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3445
3446         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3447         {
3448                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3449                 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret),
3450                         PaymentId(payment_hash.0)).unwrap();
3451                 check_added_monitors!(nodes[0], 1);
3452
3453                 let payment_event = {
3454                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3455                         assert_eq!(events.len(), 1);
3456                         SendEvent::from_event(events.remove(0))
3457                 };
3458                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3459                 assert_eq!(payment_event.msgs.len(), 1);
3460         }
3461
3462         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3463         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3464         {
3465                 nodes[0].node.send_payment_with_route(&route, failed_payment_hash,
3466                         RecipientOnionFields::secret_only(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3467                 check_added_monitors!(nodes[0], 0);
3468
3469                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3470         }
3471
3472         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3473         {
3474                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3475
3476                 let secp_ctx = Secp256k1::new();
3477                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3478                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3479                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(
3480                         &route.paths[0], 50_000, RecipientOnionFields::secret_only(payment_secret), current_height, &None).unwrap();
3481                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3482                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
3483
3484                 // Send a 0-msat update_add_htlc to fail the channel.
3485                 let update_add_htlc = msgs::UpdateAddHTLC {
3486                         channel_id: chan.2,
3487                         htlc_id: 0,
3488                         amount_msat: 0,
3489                         payment_hash,
3490                         cltv_expiry,
3491                         onion_routing_packet,
3492                         skimmed_fee_msat: None,
3493                 };
3494                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3495         }
3496         let events = nodes[0].node.get_and_clear_pending_events();
3497         assert_eq!(events.len(), 3);
3498         // Check that Alice fails backward the pending HTLC from the second payment.
3499         match events[0] {
3500                 Event::PaymentPathFailed { payment_hash, .. } => {
3501                         assert_eq!(payment_hash, failed_payment_hash);
3502                 },
3503                 _ => panic!("Unexpected event"),
3504         }
3505         match events[1] {
3506                 Event::PaymentFailed { payment_hash, .. } => {
3507                         assert_eq!(payment_hash, failed_payment_hash);
3508                 },
3509                 _ => panic!("Unexpected event"),
3510         }
3511         match events[2] {
3512                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3513                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3514                 },
3515                 _ => panic!("Unexpected event {:?}", events[1]),
3516         }
3517         check_closed_broadcast!(nodes[0], true);
3518         check_added_monitors!(nodes[0], 1);
3519 }
3520
3521 #[test]
3522 fn test_htlc_ignore_latest_remote_commitment() {
3523         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3524         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3525         let chanmon_cfgs = create_chanmon_cfgs(2);
3526         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3527         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3528         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3529         if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3530                 // We rely on the ability to connect a block redundantly, which isn't allowed via
3531                 // `chain::Listen`, so we never run the test if we randomly get assigned that
3532                 // connect_style.
3533                 return;
3534         }
3535         create_announced_chan_between_nodes(&nodes, 0, 1);
3536
3537         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3538         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3539         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3540         check_closed_broadcast!(nodes[0], true);
3541         check_added_monitors!(nodes[0], 1);
3542         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
3543
3544         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3545         assert_eq!(node_txn.len(), 3);
3546         assert_eq!(node_txn[0].txid(), node_txn[1].txid());
3547
3548         let block = create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[0].clone(), node_txn[1].clone()]);
3549         connect_block(&nodes[1], &block);
3550         check_closed_broadcast!(nodes[1], true);
3551         check_added_monitors!(nodes[1], 1);
3552         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
3553
3554         // Duplicate the connect_block call since this may happen due to other listeners
3555         // registering new transactions
3556         connect_block(&nodes[1], &block);
3557 }
3558
3559 #[test]
3560 fn test_force_close_fail_back() {
3561         // Check which HTLCs are failed-backwards on channel force-closure
3562         let chanmon_cfgs = create_chanmon_cfgs(3);
3563         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3564         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3565         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3566         create_announced_chan_between_nodes(&nodes, 0, 1);
3567         create_announced_chan_between_nodes(&nodes, 1, 2);
3568
3569         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3570
3571         let mut payment_event = {
3572                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3573                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3574                 check_added_monitors!(nodes[0], 1);
3575
3576                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3577                 assert_eq!(events.len(), 1);
3578                 SendEvent::from_event(events.remove(0))
3579         };
3580
3581         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3582         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3583
3584         expect_pending_htlcs_forwardable!(nodes[1]);
3585
3586         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3587         assert_eq!(events_2.len(), 1);
3588         payment_event = SendEvent::from_event(events_2.remove(0));
3589         assert_eq!(payment_event.msgs.len(), 1);
3590
3591         check_added_monitors!(nodes[1], 1);
3592         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3593         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3594         check_added_monitors!(nodes[2], 1);
3595         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3596
3597         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3598         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3599         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3600
3601         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3602         check_closed_broadcast!(nodes[2], true);
3603         check_added_monitors!(nodes[2], 1);
3604         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
3605         let tx = {
3606                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3607                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3608                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3609                 // back to nodes[1] upon timeout otherwise.
3610                 assert_eq!(node_txn.len(), 1);
3611                 node_txn.remove(0)
3612         };
3613
3614         mine_transaction(&nodes[1], &tx);
3615
3616         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3617         check_closed_broadcast!(nodes[1], true);
3618         check_added_monitors!(nodes[1], 1);
3619         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3620
3621         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3622         {
3623                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3624                         .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);
3625         }
3626         mine_transaction(&nodes[2], &tx);
3627         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3628         assert_eq!(node_txn.len(), 1);
3629         assert_eq!(node_txn[0].input.len(), 1);
3630         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3631         assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3632         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3633
3634         check_spends!(node_txn[0], tx);
3635 }
3636
3637 #[test]
3638 fn test_dup_events_on_peer_disconnect() {
3639         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3640         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3641         // as we used to generate the event immediately upon receipt of the payment preimage in the
3642         // update_fulfill_htlc message.
3643
3644         let chanmon_cfgs = create_chanmon_cfgs(2);
3645         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3646         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3647         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3648         create_announced_chan_between_nodes(&nodes, 0, 1);
3649
3650         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3651
3652         nodes[1].node.claim_funds(payment_preimage);
3653         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3654         check_added_monitors!(nodes[1], 1);
3655         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3656         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3657         expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
3658
3659         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3660         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3661
3662         let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3663         reconnect_args.pending_htlc_claims.0 = 1;
3664         reconnect_nodes(reconnect_args);
3665         expect_payment_path_successful!(nodes[0]);
3666 }
3667
3668 #[test]
3669 fn test_peer_disconnected_before_funding_broadcasted() {
3670         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3671         // before the funding transaction has been broadcasted.
3672         let chanmon_cfgs = create_chanmon_cfgs(2);
3673         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3674         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3675         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3676
3677         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3678         // broadcasted, even though it's created by `nodes[0]`.
3679         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();
3680         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3681         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3682         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3683         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3684
3685         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3686         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3687
3688         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3689
3690         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3691         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3692
3693         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3694         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3695         // broadcasted.
3696         {
3697                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3698         }
3699
3700         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3701         // disconnected before the funding transaction was broadcasted.
3702         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3703         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3704
3705         check_closed_event!(&nodes[0], 1, ClosureReason::DisconnectedPeer, false
3706                 , [nodes[1].node.get_our_node_id()], 1000000);
3707         check_closed_event!(&nodes[1], 1, ClosureReason::DisconnectedPeer, false
3708                 , [nodes[0].node.get_our_node_id()], 1000000);
3709 }
3710
3711 #[test]
3712 fn test_simple_peer_disconnect() {
3713         // Test that we can reconnect when there are no lost messages
3714         let chanmon_cfgs = create_chanmon_cfgs(3);
3715         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3716         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3717         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3718         create_announced_chan_between_nodes(&nodes, 0, 1);
3719         create_announced_chan_between_nodes(&nodes, 1, 2);
3720
3721         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3722         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3723         let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3724         reconnect_args.send_channel_ready = (true, true);
3725         reconnect_nodes(reconnect_args);
3726
3727         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3728         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3729         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3730         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3731
3732         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3733         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3734         reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3735
3736         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3737         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3738         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3739         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3740
3741         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3742         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3743
3744         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3745         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3746
3747         let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3748         reconnect_args.pending_cell_htlc_fails.0 = 1;
3749         reconnect_args.pending_cell_htlc_claims.0 = 1;
3750         reconnect_nodes(reconnect_args);
3751         {
3752                 let events = nodes[0].node.get_and_clear_pending_events();
3753                 assert_eq!(events.len(), 4);
3754                 match events[0] {
3755                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3756                                 assert_eq!(payment_preimage, payment_preimage_3);
3757                                 assert_eq!(payment_hash, payment_hash_3);
3758                         },
3759                         _ => panic!("Unexpected event"),
3760                 }
3761                 match events[1] {
3762                         Event::PaymentPathSuccessful { .. } => {},
3763                         _ => panic!("Unexpected event"),
3764                 }
3765                 match events[2] {
3766                         Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3767                                 assert_eq!(payment_hash, payment_hash_5);
3768                                 assert!(payment_failed_permanently);
3769                         },
3770                         _ => panic!("Unexpected event"),
3771                 }
3772                 match events[3] {
3773                         Event::PaymentFailed { payment_hash, .. } => {
3774                                 assert_eq!(payment_hash, payment_hash_5);
3775                         },
3776                         _ => panic!("Unexpected event"),
3777                 }
3778         }
3779         check_added_monitors(&nodes[0], 1);
3780
3781         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3782         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3783 }
3784
3785 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3786         // Test that we can reconnect when in-flight HTLC updates get dropped
3787         let chanmon_cfgs = create_chanmon_cfgs(2);
3788         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3789         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3790         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3791
3792         let mut as_channel_ready = None;
3793         let channel_id = if messages_delivered == 0 {
3794                 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3795                 as_channel_ready = Some(channel_ready);
3796                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3797                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3798                 // it before the channel_reestablish message.
3799                 chan_id
3800         } else {
3801                 create_announced_chan_between_nodes(&nodes, 0, 1).2
3802         };
3803
3804         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3805
3806         let payment_event = {
3807                 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3808                         RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3809                 check_added_monitors!(nodes[0], 1);
3810
3811                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3812                 assert_eq!(events.len(), 1);
3813                 SendEvent::from_event(events.remove(0))
3814         };
3815         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3816
3817         if messages_delivered < 2 {
3818                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3819         } else {
3820                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3821                 if messages_delivered >= 3 {
3822                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3823                         check_added_monitors!(nodes[1], 1);
3824                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3825
3826                         if messages_delivered >= 4 {
3827                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3828                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3829                                 check_added_monitors!(nodes[0], 1);
3830
3831                                 if messages_delivered >= 5 {
3832                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3833                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3834                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3835                                         check_added_monitors!(nodes[0], 1);
3836
3837                                         if messages_delivered >= 6 {
3838                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3839                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3840                                                 check_added_monitors!(nodes[1], 1);
3841                                         }
3842                                 }
3843                         }
3844                 }
3845         }
3846
3847         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3848         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3849         if messages_delivered < 3 {
3850                 if simulate_broken_lnd {
3851                         // lnd has a long-standing bug where they send a channel_ready prior to a
3852                         // channel_reestablish if you reconnect prior to channel_ready time.
3853                         //
3854                         // Here we simulate that behavior, delivering a channel_ready immediately on
3855                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3856                         // in `reconnect_nodes` but we currently don't fail based on that.
3857                         //
3858                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3859                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3860                 }
3861                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3862                 // received on either side, both sides will need to resend them.
3863                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3864                 reconnect_args.send_channel_ready = (true, true);
3865                 reconnect_args.pending_htlc_adds.1 = 1;
3866                 reconnect_nodes(reconnect_args);
3867         } else if messages_delivered == 3 {
3868                 // nodes[0] still wants its RAA + commitment_signed
3869                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3870                 reconnect_args.pending_htlc_adds.0 = -1;
3871                 reconnect_args.pending_raa.0 = true;
3872                 reconnect_nodes(reconnect_args);
3873         } else if messages_delivered == 4 {
3874                 // nodes[0] still wants its commitment_signed
3875                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3876                 reconnect_args.pending_htlc_adds.0 = -1;
3877                 reconnect_nodes(reconnect_args);
3878         } else if messages_delivered == 5 {
3879                 // nodes[1] still wants its final RAA
3880                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3881                 reconnect_args.pending_raa.1 = true;
3882                 reconnect_nodes(reconnect_args);
3883         } else if messages_delivered == 6 {
3884                 // Everything was delivered...
3885                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3886         }
3887
3888         let events_1 = nodes[1].node.get_and_clear_pending_events();
3889         if messages_delivered == 0 {
3890                 assert_eq!(events_1.len(), 2);
3891                 match events_1[0] {
3892                         Event::ChannelReady { .. } => { },
3893                         _ => panic!("Unexpected event"),
3894                 };
3895                 match events_1[1] {
3896                         Event::PendingHTLCsForwardable { .. } => { },
3897                         _ => panic!("Unexpected event"),
3898                 };
3899         } else {
3900                 assert_eq!(events_1.len(), 1);
3901                 match events_1[0] {
3902                         Event::PendingHTLCsForwardable { .. } => { },
3903                         _ => panic!("Unexpected event"),
3904                 };
3905         }
3906
3907         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3908         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3909         reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3910
3911         nodes[1].node.process_pending_htlc_forwards();
3912
3913         let events_2 = nodes[1].node.get_and_clear_pending_events();
3914         assert_eq!(events_2.len(), 1);
3915         match events_2[0] {
3916                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3917                         assert_eq!(payment_hash_1, *payment_hash);
3918                         assert_eq!(amount_msat, 1_000_000);
3919                         assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3920                         assert_eq!(via_channel_id, Some(channel_id));
3921                         match &purpose {
3922                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3923                                         assert!(payment_preimage.is_none());
3924                                         assert_eq!(payment_secret_1, *payment_secret);
3925                                 },
3926                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3927                         }
3928                 },
3929                 _ => panic!("Unexpected event"),
3930         }
3931
3932         nodes[1].node.claim_funds(payment_preimage_1);
3933         check_added_monitors!(nodes[1], 1);
3934         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3935
3936         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3937         assert_eq!(events_3.len(), 1);
3938         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3939                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3940                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3941                         assert!(updates.update_add_htlcs.is_empty());
3942                         assert!(updates.update_fail_htlcs.is_empty());
3943                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3944                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3945                         assert!(updates.update_fee.is_none());
3946                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3947                 },
3948                 _ => panic!("Unexpected event"),
3949         };
3950
3951         if messages_delivered >= 1 {
3952                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3953
3954                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3955                 assert_eq!(events_4.len(), 1);
3956                 match events_4[0] {
3957                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3958                                 assert_eq!(payment_preimage_1, *payment_preimage);
3959                                 assert_eq!(payment_hash_1, *payment_hash);
3960                         },
3961                         _ => panic!("Unexpected event"),
3962                 }
3963
3964                 if messages_delivered >= 2 {
3965                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3966                         check_added_monitors!(nodes[0], 1);
3967                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3968
3969                         if messages_delivered >= 3 {
3970                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3971                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3972                                 check_added_monitors!(nodes[1], 1);
3973
3974                                 if messages_delivered >= 4 {
3975                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3976                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3977                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3978                                         check_added_monitors!(nodes[1], 1);
3979
3980                                         if messages_delivered >= 5 {
3981                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3982                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3983                                                 check_added_monitors!(nodes[0], 1);
3984                                         }
3985                                 }
3986                         }
3987                 }
3988         }
3989
3990         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3991         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3992         if messages_delivered < 2 {
3993                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3994                 reconnect_args.pending_htlc_claims.0 = 1;
3995                 reconnect_nodes(reconnect_args);
3996                 if messages_delivered < 1 {
3997                         expect_payment_sent!(nodes[0], payment_preimage_1);
3998                 } else {
3999                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4000                 }
4001         } else if messages_delivered == 2 {
4002                 // nodes[0] still wants its RAA + commitment_signed
4003                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4004                 reconnect_args.pending_htlc_adds.1 = -1;
4005                 reconnect_args.pending_raa.1 = true;
4006                 reconnect_nodes(reconnect_args);
4007         } else if messages_delivered == 3 {
4008                 // nodes[0] still wants its commitment_signed
4009                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4010                 reconnect_args.pending_htlc_adds.1 = -1;
4011                 reconnect_nodes(reconnect_args);
4012         } else if messages_delivered == 4 {
4013                 // nodes[1] still wants its final RAA
4014                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4015                 reconnect_args.pending_raa.0 = true;
4016                 reconnect_nodes(reconnect_args);
4017         } else if messages_delivered == 5 {
4018                 // Everything was delivered...
4019                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
4020         }
4021
4022         if messages_delivered == 1 || messages_delivered == 2 {
4023                 expect_payment_path_successful!(nodes[0]);
4024         }
4025         if messages_delivered <= 5 {
4026                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4027                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4028         }
4029         reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
4030
4031         if messages_delivered > 2 {
4032                 expect_payment_path_successful!(nodes[0]);
4033         }
4034
4035         // Channel should still work fine...
4036         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4037         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
4038         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4039 }
4040
4041 #[test]
4042 fn test_drop_messages_peer_disconnect_a() {
4043         do_test_drop_messages_peer_disconnect(0, true);
4044         do_test_drop_messages_peer_disconnect(0, false);
4045         do_test_drop_messages_peer_disconnect(1, false);
4046         do_test_drop_messages_peer_disconnect(2, false);
4047 }
4048
4049 #[test]
4050 fn test_drop_messages_peer_disconnect_b() {
4051         do_test_drop_messages_peer_disconnect(3, false);
4052         do_test_drop_messages_peer_disconnect(4, false);
4053         do_test_drop_messages_peer_disconnect(5, false);
4054         do_test_drop_messages_peer_disconnect(6, false);
4055 }
4056
4057 #[test]
4058 fn test_channel_ready_without_best_block_updated() {
4059         // Previously, if we were offline when a funding transaction was locked in, and then we came
4060         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4061         // generate a channel_ready until a later best_block_updated. This tests that we generate the
4062         // channel_ready immediately instead.
4063         let chanmon_cfgs = create_chanmon_cfgs(2);
4064         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4065         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4066         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4067         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4068
4069         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4070
4071         let conf_height = nodes[0].best_block_info().1 + 1;
4072         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4073         let block_txn = [funding_tx];
4074         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4075         let conf_block_header = nodes[0].get_block_header(conf_height);
4076         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4077
4078         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4079         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4080         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4081 }
4082
4083 #[test]
4084 fn test_channel_monitor_skipping_block_when_channel_manager_is_leading() {
4085         let chanmon_cfgs = create_chanmon_cfgs(2);
4086         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4087         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4088         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4089
4090         // Let channel_manager get ahead of chain_monitor by 1 block.
4091         // This is to emulate race-condition where newly added channel_monitor skips processing 1 block,
4092         // in case where client calls block_connect on channel_manager first and then on chain_monitor.
4093         let height_1 = nodes[0].best_block_info().1 + 1;
4094         let mut block_1 = create_dummy_block(nodes[0].best_block_hash(), height_1, Vec::new());
4095
4096         nodes[0].blocks.lock().unwrap().push((block_1.clone(), height_1));
4097         nodes[0].node.block_connected(&block_1, height_1);
4098
4099         // Create channel, and it gets added to chain_monitor in funding_created.
4100         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4101
4102         // Now, newly added channel_monitor in chain_monitor hasn't processed block_1,
4103         // but it's best_block is block_1, since that was populated by channel_manager, and channel_manager
4104         // was running ahead of chain_monitor at the time of funding_created.
4105         // Later on, subsequent blocks are connected to both channel_manager and chain_monitor.
4106         // Hence, this channel's channel_monitor skipped block_1, directly tries to process subsequent blocks.
4107         confirm_transaction_at(&nodes[0], &funding_tx, nodes[0].best_block_info().1 + 1);
4108         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4109
4110         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4111         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4112         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4113 }
4114
4115 #[test]
4116 fn test_channel_monitor_skipping_block_when_channel_manager_is_lagging() {
4117         let chanmon_cfgs = create_chanmon_cfgs(2);
4118         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4119         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4120         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4121
4122         // Let chain_monitor get ahead of channel_manager by 1 block.
4123         // This is to emulate race-condition where newly added channel_monitor skips processing 1 block,
4124         // in case where client calls block_connect on chain_monitor first and then on channel_manager.
4125         let height_1 = nodes[0].best_block_info().1 + 1;
4126         let mut block_1 = create_dummy_block(nodes[0].best_block_hash(), height_1, Vec::new());
4127
4128         nodes[0].blocks.lock().unwrap().push((block_1.clone(), height_1));
4129         nodes[0].chain_monitor.chain_monitor.block_connected(&block_1, height_1);
4130
4131         // Create channel, and it gets added to chain_monitor in funding_created.
4132         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4133
4134         // channel_manager can't really skip block_1, it should get it eventually.
4135         nodes[0].node.block_connected(&block_1, height_1);
4136
4137         // Now, newly added channel_monitor in chain_monitor hasn't processed block_1, it's best_block is
4138         // the block before block_1, since that was populated by channel_manager, and channel_manager was
4139         // running behind at the time of funding_created.
4140         // Later on, subsequent blocks are connected to both channel_manager and chain_monitor.
4141         // Hence, this channel's channel_monitor skipped block_1, directly tries to process subsequent blocks.
4142         confirm_transaction_at(&nodes[0], &funding_tx, nodes[0].best_block_info().1 + 1);
4143         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4144
4145         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4146         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4147         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4148 }
4149
4150 #[test]
4151 fn test_drop_messages_peer_disconnect_dual_htlc() {
4152         // Test that we can handle reconnecting when both sides of a channel have pending
4153         // commitment_updates when we disconnect.
4154         let chanmon_cfgs = create_chanmon_cfgs(2);
4155         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4156         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4157         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4158         create_announced_chan_between_nodes(&nodes, 0, 1);
4159
4160         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4161
4162         // Now try to send a second payment which will fail to send
4163         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4164         nodes[0].node.send_payment_with_route(&route, payment_hash_2,
4165                 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
4166         check_added_monitors!(nodes[0], 1);
4167
4168         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4169         assert_eq!(events_1.len(), 1);
4170         match events_1[0] {
4171                 MessageSendEvent::UpdateHTLCs { .. } => {},
4172                 _ => panic!("Unexpected event"),
4173         }
4174
4175         nodes[1].node.claim_funds(payment_preimage_1);
4176         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4177         check_added_monitors!(nodes[1], 1);
4178
4179         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4180         assert_eq!(events_2.len(), 1);
4181         match events_2[0] {
4182                 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 } } => {
4183                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4184                         assert!(update_add_htlcs.is_empty());
4185                         assert_eq!(update_fulfill_htlcs.len(), 1);
4186                         assert!(update_fail_htlcs.is_empty());
4187                         assert!(update_fail_malformed_htlcs.is_empty());
4188                         assert!(update_fee.is_none());
4189
4190                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4191                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4192                         assert_eq!(events_3.len(), 1);
4193                         match events_3[0] {
4194                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4195                                         assert_eq!(*payment_preimage, payment_preimage_1);
4196                                         assert_eq!(*payment_hash, payment_hash_1);
4197                                 },
4198                                 _ => panic!("Unexpected event"),
4199                         }
4200
4201                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4202                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4203                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4204                         check_added_monitors!(nodes[0], 1);
4205                 },
4206                 _ => panic!("Unexpected event"),
4207         }
4208
4209         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4210         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4211
4212         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
4213                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
4214         }, true).unwrap();
4215         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4216         assert_eq!(reestablish_1.len(), 1);
4217         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
4218                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
4219         }, false).unwrap();
4220         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4221         assert_eq!(reestablish_2.len(), 1);
4222
4223         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4224         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4225         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4226         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4227
4228         assert!(as_resp.0.is_none());
4229         assert!(bs_resp.0.is_none());
4230
4231         assert!(bs_resp.1.is_none());
4232         assert!(bs_resp.2.is_none());
4233
4234         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4235
4236         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4237         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4238         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4239         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4240         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4241         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4242         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4243         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4244         // No commitment_signed so get_event_msg's assert(len == 1) passes
4245         check_added_monitors!(nodes[1], 1);
4246
4247         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4248         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4249         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4250         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4251         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4252         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4253         assert!(bs_second_commitment_signed.update_fee.is_none());
4254         check_added_monitors!(nodes[1], 1);
4255
4256         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4257         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4258         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4259         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4260         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4261         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4262         assert!(as_commitment_signed.update_fee.is_none());
4263         check_added_monitors!(nodes[0], 1);
4264
4265         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4266         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4267         // No commitment_signed so get_event_msg's assert(len == 1) passes
4268         check_added_monitors!(nodes[0], 1);
4269
4270         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4271         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4272         // No commitment_signed so get_event_msg's assert(len == 1) passes
4273         check_added_monitors!(nodes[1], 1);
4274
4275         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4276         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4277         check_added_monitors!(nodes[1], 1);
4278
4279         expect_pending_htlcs_forwardable!(nodes[1]);
4280
4281         let events_5 = nodes[1].node.get_and_clear_pending_events();
4282         assert_eq!(events_5.len(), 1);
4283         match events_5[0] {
4284                 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4285                         assert_eq!(payment_hash_2, *payment_hash);
4286                         match &purpose {
4287                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4288                                         assert!(payment_preimage.is_none());
4289                                         assert_eq!(payment_secret_2, *payment_secret);
4290                                 },
4291                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4292                         }
4293                 },
4294                 _ => panic!("Unexpected event"),
4295         }
4296
4297         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4298         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4299         check_added_monitors!(nodes[0], 1);
4300
4301         expect_payment_path_successful!(nodes[0]);
4302         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4303 }
4304
4305 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4306         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4307         // to avoid our counterparty failing the channel.
4308         let chanmon_cfgs = create_chanmon_cfgs(2);
4309         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4310         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4311         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4312
4313         create_announced_chan_between_nodes(&nodes, 0, 1);
4314
4315         let our_payment_hash = if send_partial_mpp {
4316                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4317                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4318                 // indicates there are more HTLCs coming.
4319                 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.
4320                 let payment_id = PaymentId([42; 32]);
4321                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4322                         RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4323                 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4324                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4325                         &None, session_privs[0]).unwrap();
4326                 check_added_monitors!(nodes[0], 1);
4327                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4328                 assert_eq!(events.len(), 1);
4329                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4330                 // hop should *not* yet generate any PaymentClaimable event(s).
4331                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4332                 our_payment_hash
4333         } else {
4334                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4335         };
4336
4337         let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
4338         connect_block(&nodes[0], &block);
4339         connect_block(&nodes[1], &block);
4340         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4341         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4342                 block.header.prev_blockhash = block.block_hash();
4343                 connect_block(&nodes[0], &block);
4344                 connect_block(&nodes[1], &block);
4345         }
4346
4347         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4348
4349         check_added_monitors!(nodes[1], 1);
4350         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4351         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4352         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4353         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4354         assert!(htlc_timeout_updates.update_fee.is_none());
4355
4356         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4357         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4358         // 100_000 msat as u64, followed by the height at which we failed back above
4359         let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4360         expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4361         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4362 }
4363
4364 #[test]
4365 fn test_htlc_timeout() {
4366         do_test_htlc_timeout(true);
4367         do_test_htlc_timeout(false);
4368 }
4369
4370 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4371         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4372         let chanmon_cfgs = create_chanmon_cfgs(3);
4373         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4374         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4375         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4376         create_announced_chan_between_nodes(&nodes, 0, 1);
4377         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4378
4379         // Make sure all nodes are at the same starting height
4380         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4381         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4382         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4383
4384         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4385         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4386         nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4387                 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4388         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4389         check_added_monitors!(nodes[1], 1);
4390
4391         // Now attempt to route a second payment, which should be placed in the holding cell
4392         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4393         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4394         sending_node.node.send_payment_with_route(&route, second_payment_hash,
4395                 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4396         if forwarded_htlc {
4397                 check_added_monitors!(nodes[0], 1);
4398                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4399                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4400                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4401                 expect_pending_htlcs_forwardable!(nodes[1]);
4402         }
4403         check_added_monitors!(nodes[1], 0);
4404
4405         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4406         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4407         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4408         connect_blocks(&nodes[1], 1);
4409
4410         if forwarded_htlc {
4411                 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 }]);
4412                 check_added_monitors!(nodes[1], 1);
4413                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4414                 assert_eq!(fail_commit.len(), 1);
4415                 match fail_commit[0] {
4416                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4417                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4418                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4419                         },
4420                         _ => unreachable!(),
4421                 }
4422                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4423         } else {
4424                 expect_payment_failed!(nodes[1], second_payment_hash, false);
4425         }
4426 }
4427
4428 #[test]
4429 fn test_holding_cell_htlc_add_timeouts() {
4430         do_test_holding_cell_htlc_add_timeouts(false);
4431         do_test_holding_cell_htlc_add_timeouts(true);
4432 }
4433
4434 macro_rules! check_spendable_outputs {
4435         ($node: expr, $keysinterface: expr) => {
4436                 {
4437                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4438                         let mut txn = Vec::new();
4439                         let mut all_outputs = Vec::new();
4440                         let secp_ctx = Secp256k1::new();
4441                         for event in events.drain(..) {
4442                                 match event {
4443                                         Event::SpendableOutputs { mut outputs, channel_id: _ } => {
4444                                                 for outp in outputs.drain(..) {
4445                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, None, &secp_ctx).unwrap());
4446                                                         all_outputs.push(outp);
4447                                                 }
4448                                         },
4449                                         _ => panic!("Unexpected event"),
4450                                 };
4451                         }
4452                         if all_outputs.len() > 1 {
4453                                 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, None, &secp_ctx) {
4454                                         txn.push(tx);
4455                                 }
4456                         }
4457                         txn
4458                 }
4459         }
4460 }
4461
4462 #[test]
4463 fn test_claim_sizeable_push_msat() {
4464         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4465         let chanmon_cfgs = create_chanmon_cfgs(2);
4466         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4467         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4468         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4469
4470         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4471         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4472         check_closed_broadcast!(nodes[1], true);
4473         check_added_monitors!(nodes[1], 1);
4474         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
4475         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4476         assert_eq!(node_txn.len(), 1);
4477         check_spends!(node_txn[0], chan.3);
4478         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
4479
4480         mine_transaction(&nodes[1], &node_txn[0]);
4481         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4482
4483         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4484         assert_eq!(spend_txn.len(), 1);
4485         assert_eq!(spend_txn[0].input.len(), 1);
4486         check_spends!(spend_txn[0], node_txn[0]);
4487         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4488 }
4489
4490 #[test]
4491 fn test_claim_on_remote_sizeable_push_msat() {
4492         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4493         // to_remote output is encumbered by a P2WPKH
4494         let chanmon_cfgs = create_chanmon_cfgs(2);
4495         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4496         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4497         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4498
4499         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4500         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4501         check_closed_broadcast!(nodes[0], true);
4502         check_added_monitors!(nodes[0], 1);
4503         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
4504
4505         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4506         assert_eq!(node_txn.len(), 1);
4507         check_spends!(node_txn[0], chan.3);
4508         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
4509
4510         mine_transaction(&nodes[1], &node_txn[0]);
4511         check_closed_broadcast!(nodes[1], true);
4512         check_added_monitors!(nodes[1], 1);
4513         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4514         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4515
4516         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4517         assert_eq!(spend_txn.len(), 1);
4518         check_spends!(spend_txn[0], node_txn[0]);
4519 }
4520
4521 #[test]
4522 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4523         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4524         // to_remote output is encumbered by a P2WPKH
4525
4526         let chanmon_cfgs = create_chanmon_cfgs(2);
4527         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4528         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4529         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4530
4531         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4532         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4533         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4534         assert_eq!(revoked_local_txn[0].input.len(), 1);
4535         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4536
4537         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4538         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4539         check_closed_broadcast!(nodes[1], true);
4540         check_added_monitors!(nodes[1], 1);
4541         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4542
4543         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4544         mine_transaction(&nodes[1], &node_txn[0]);
4545         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4546
4547         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4548         assert_eq!(spend_txn.len(), 3);
4549         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4550         check_spends!(spend_txn[1], node_txn[0]);
4551         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4552 }
4553
4554 #[test]
4555 fn test_static_spendable_outputs_preimage_tx() {
4556         let chanmon_cfgs = create_chanmon_cfgs(2);
4557         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4558         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4559         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4560
4561         // Create some initial channels
4562         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4563
4564         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4565
4566         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4567         assert_eq!(commitment_tx[0].input.len(), 1);
4568         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4569
4570         // Settle A's commitment tx on B's chain
4571         nodes[1].node.claim_funds(payment_preimage);
4572         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4573         check_added_monitors!(nodes[1], 1);
4574         mine_transaction(&nodes[1], &commitment_tx[0]);
4575         check_added_monitors!(nodes[1], 1);
4576         let events = nodes[1].node.get_and_clear_pending_msg_events();
4577         match events[0] {
4578                 MessageSendEvent::UpdateHTLCs { .. } => {},
4579                 _ => panic!("Unexpected event"),
4580         }
4581         match events[1] {
4582                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4583                 _ => panic!("Unexepected event"),
4584         }
4585
4586         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4587         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4588         assert_eq!(node_txn.len(), 1);
4589         check_spends!(node_txn[0], commitment_tx[0]);
4590         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4591
4592         mine_transaction(&nodes[1], &node_txn[0]);
4593         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4594         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4595
4596         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4597         assert_eq!(spend_txn.len(), 1);
4598         check_spends!(spend_txn[0], node_txn[0]);
4599 }
4600
4601 #[test]
4602 fn test_static_spendable_outputs_timeout_tx() {
4603         let chanmon_cfgs = create_chanmon_cfgs(2);
4604         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4605         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4606         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4607
4608         // Create some initial channels
4609         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4610
4611         // Rebalance the network a bit by relaying one payment through all the channels ...
4612         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4613
4614         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4615
4616         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4617         assert_eq!(commitment_tx[0].input.len(), 1);
4618         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4619
4620         // Settle A's commitment tx on B' chain
4621         mine_transaction(&nodes[1], &commitment_tx[0]);
4622         check_added_monitors!(nodes[1], 1);
4623         let events = nodes[1].node.get_and_clear_pending_msg_events();
4624         match events[0] {
4625                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4626                 _ => panic!("Unexpected event"),
4627         }
4628         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4629
4630         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4631         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4632         assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4633         check_spends!(node_txn[0],  commitment_tx[0].clone());
4634         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4635
4636         mine_transaction(&nodes[1], &node_txn[0]);
4637         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4638         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4639         expect_payment_failed!(nodes[1], our_payment_hash, false);
4640
4641         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4642         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4643         check_spends!(spend_txn[0], commitment_tx[0]);
4644         check_spends!(spend_txn[1], node_txn[0]);
4645         check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4646 }
4647
4648 #[test]
4649 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4650         let chanmon_cfgs = create_chanmon_cfgs(2);
4651         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4652         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4653         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4654
4655         // Create some initial channels
4656         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4657
4658         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4659         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4660         assert_eq!(revoked_local_txn[0].input.len(), 1);
4661         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4662
4663         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4664
4665         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4666         check_closed_broadcast!(nodes[1], true);
4667         check_added_monitors!(nodes[1], 1);
4668         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4669
4670         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4671         assert_eq!(node_txn.len(), 1);
4672         assert_eq!(node_txn[0].input.len(), 2);
4673         check_spends!(node_txn[0], revoked_local_txn[0]);
4674
4675         mine_transaction(&nodes[1], &node_txn[0]);
4676         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4677
4678         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4679         assert_eq!(spend_txn.len(), 1);
4680         check_spends!(spend_txn[0], node_txn[0]);
4681 }
4682
4683 #[test]
4684 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4685         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4686         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4687         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4688         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4689         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4690
4691         // Create some initial channels
4692         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4693
4694         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4695         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4696         assert_eq!(revoked_local_txn[0].input.len(), 1);
4697         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4698
4699         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4700
4701         // A will generate HTLC-Timeout from revoked commitment tx
4702         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4703         check_closed_broadcast!(nodes[0], true);
4704         check_added_monitors!(nodes[0], 1);
4705         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4706         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4707
4708         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4709         assert_eq!(revoked_htlc_txn.len(), 1);
4710         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4711         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4712         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4713         assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4714
4715         // B will generate justice tx from A's revoked commitment/HTLC tx
4716         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4717         check_closed_broadcast!(nodes[1], true);
4718         check_added_monitors!(nodes[1], 1);
4719         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4720
4721         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4722         assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4723         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4724         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4725         // transactions next...
4726         assert_eq!(node_txn[0].input.len(), 3);
4727         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4728
4729         assert_eq!(node_txn[1].input.len(), 2);
4730         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4731         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4732                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4733         } else {
4734                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4735                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4736         }
4737
4738         mine_transaction(&nodes[1], &node_txn[1]);
4739         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4740
4741         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4742         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4743         assert_eq!(spend_txn.len(), 1);
4744         assert_eq!(spend_txn[0].input.len(), 1);
4745         check_spends!(spend_txn[0], node_txn[1]);
4746 }
4747
4748 #[test]
4749 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4750         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4751         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4752         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4753         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4754         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4755
4756         // Create some initial channels
4757         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4758
4759         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4760         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4761         assert_eq!(revoked_local_txn[0].input.len(), 1);
4762         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4763
4764         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4765         assert_eq!(revoked_local_txn[0].output.len(), 2);
4766
4767         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4768
4769         // B will generate HTLC-Success from revoked commitment tx
4770         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4771         check_closed_broadcast!(nodes[1], true);
4772         check_added_monitors!(nodes[1], 1);
4773         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4774         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4775
4776         assert_eq!(revoked_htlc_txn.len(), 1);
4777         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4778         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4779         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4780
4781         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4782         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4783         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4784
4785         // A will generate justice tx from B's revoked commitment/HTLC tx
4786         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4787         check_closed_broadcast!(nodes[0], true);
4788         check_added_monitors!(nodes[0], 1);
4789         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4790
4791         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4792         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4793
4794         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4795         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4796         // transactions next...
4797         assert_eq!(node_txn[0].input.len(), 2);
4798         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4799         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4800                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4801         } else {
4802                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4803                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4804         }
4805
4806         assert_eq!(node_txn[1].input.len(), 1);
4807         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4808
4809         mine_transaction(&nodes[0], &node_txn[1]);
4810         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4811
4812         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4813         // didn't try to generate any new transactions.
4814
4815         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4816         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4817         assert_eq!(spend_txn.len(), 3);
4818         assert_eq!(spend_txn[0].input.len(), 1);
4819         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4820         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4821         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4822         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4823 }
4824
4825 #[test]
4826 fn test_onchain_to_onchain_claim() {
4827         // Test that in case of channel closure, we detect the state of output and claim HTLC
4828         // on downstream peer's remote commitment tx.
4829         // First, have C claim an HTLC against its own latest commitment transaction.
4830         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4831         // channel.
4832         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4833         // gets broadcast.
4834
4835         let chanmon_cfgs = create_chanmon_cfgs(3);
4836         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4837         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4838         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4839
4840         // Create some initial channels
4841         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4842         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4843
4844         // Ensure all nodes are at the same height
4845         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4846         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4847         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4848         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4849
4850         // Rebalance the network a bit by relaying one payment through all the channels ...
4851         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4852         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4853
4854         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4855         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4856         check_spends!(commitment_tx[0], chan_2.3);
4857         nodes[2].node.claim_funds(payment_preimage);
4858         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4859         check_added_monitors!(nodes[2], 1);
4860         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4861         assert!(updates.update_add_htlcs.is_empty());
4862         assert!(updates.update_fail_htlcs.is_empty());
4863         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4864         assert!(updates.update_fail_malformed_htlcs.is_empty());
4865
4866         mine_transaction(&nodes[2], &commitment_tx[0]);
4867         check_closed_broadcast!(nodes[2], true);
4868         check_added_monitors!(nodes[2], 1);
4869         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4870
4871         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4872         assert_eq!(c_txn.len(), 1);
4873         check_spends!(c_txn[0], commitment_tx[0]);
4874         assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4875         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4876         assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4877
4878         // 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
4879         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), c_txn[0].clone()]));
4880         check_added_monitors!(nodes[1], 1);
4881         let events = nodes[1].node.get_and_clear_pending_events();
4882         assert_eq!(events.len(), 2);
4883         match events[0] {
4884                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4885                 _ => panic!("Unexpected event"),
4886         }
4887         match events[1] {
4888                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4889                         assert_eq!(fee_earned_msat, Some(1000));
4890                         assert_eq!(prev_channel_id, Some(chan_1.2));
4891                         assert_eq!(claim_from_onchain_tx, true);
4892                         assert_eq!(next_channel_id, Some(chan_2.2));
4893                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4894                 },
4895                 _ => panic!("Unexpected event"),
4896         }
4897         check_added_monitors!(nodes[1], 1);
4898         let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4899         assert_eq!(msg_events.len(), 3);
4900         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4901         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4902
4903         match nodes_2_event {
4904                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4905                 _ => panic!("Unexpected event"),
4906         }
4907
4908         match nodes_0_event {
4909                 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, .. } } => {
4910                         assert!(update_add_htlcs.is_empty());
4911                         assert!(update_fail_htlcs.is_empty());
4912                         assert_eq!(update_fulfill_htlcs.len(), 1);
4913                         assert!(update_fail_malformed_htlcs.is_empty());
4914                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4915                 },
4916                 _ => panic!("Unexpected event"),
4917         };
4918
4919         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4920         match msg_events[0] {
4921                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4922                 _ => panic!("Unexpected event"),
4923         }
4924
4925         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4926         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4927         mine_transaction(&nodes[1], &commitment_tx[0]);
4928         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4929         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4930         // ChannelMonitor: HTLC-Success tx
4931         assert_eq!(b_txn.len(), 1);
4932         check_spends!(b_txn[0], commitment_tx[0]);
4933         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4934         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4935         assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1); // Success tx
4936
4937         check_closed_broadcast!(nodes[1], true);
4938         check_added_monitors!(nodes[1], 1);
4939 }
4940
4941 #[test]
4942 fn test_duplicate_payment_hash_one_failure_one_success() {
4943         // Topology : A --> B --> C --> D
4944         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4945         // Note that because C will refuse to generate two payment secrets for the same payment hash,
4946         // we forward one of the payments onwards to D.
4947         let chanmon_cfgs = create_chanmon_cfgs(4);
4948         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4949         // When this test was written, the default base fee floated based on the HTLC count.
4950         // It is now fixed, so we simply set the fee to the expected value here.
4951         let mut config = test_default_channel_config();
4952         config.channel_config.forwarding_fee_base_msat = 196;
4953         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4954                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4955         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4956
4957         create_announced_chan_between_nodes(&nodes, 0, 1);
4958         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4959         create_announced_chan_between_nodes(&nodes, 2, 3);
4960
4961         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4962         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4963         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4964         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4965         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4966
4967         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4968
4969         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4970         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4971         // script push size limit so that the below script length checks match
4972         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4973         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4974                 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
4975         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000);
4976         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4977
4978         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4979         assert_eq!(commitment_txn[0].input.len(), 1);
4980         check_spends!(commitment_txn[0], chan_2.3);
4981
4982         mine_transaction(&nodes[1], &commitment_txn[0]);
4983         check_closed_broadcast!(nodes[1], true);
4984         check_added_monitors!(nodes[1], 1);
4985         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
4986         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
4987
4988         let htlc_timeout_tx;
4989         { // Extract one of the two HTLC-Timeout transaction
4990                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4991                 // ChannelMonitor: timeout tx * 2-or-3
4992                 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4993
4994                 check_spends!(node_txn[0], commitment_txn[0]);
4995                 assert_eq!(node_txn[0].input.len(), 1);
4996                 assert_eq!(node_txn[0].output.len(), 1);
4997
4998                 if node_txn.len() > 2 {
4999                         check_spends!(node_txn[1], commitment_txn[0]);
5000                         assert_eq!(node_txn[1].input.len(), 1);
5001                         assert_eq!(node_txn[1].output.len(), 1);
5002                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
5003
5004                         check_spends!(node_txn[2], commitment_txn[0]);
5005                         assert_eq!(node_txn[2].input.len(), 1);
5006                         assert_eq!(node_txn[2].output.len(), 1);
5007                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
5008                 } else {
5009                         check_spends!(node_txn[1], commitment_txn[0]);
5010                         assert_eq!(node_txn[1].input.len(), 1);
5011                         assert_eq!(node_txn[1].output.len(), 1);
5012                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
5013                 }
5014
5015                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5016                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5017                 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
5018                 // (with value 900 sats) will be claimed in the below `claim_funds` call.
5019                 if node_txn.len() > 2 {
5020                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5021                         htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
5022                 } else {
5023                         htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
5024                 }
5025         }
5026
5027         nodes[2].node.claim_funds(our_payment_preimage);
5028         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5029
5030         mine_transaction(&nodes[2], &commitment_txn[0]);
5031         check_added_monitors!(nodes[2], 2);
5032         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5033         let events = nodes[2].node.get_and_clear_pending_msg_events();
5034         match events[0] {
5035                 MessageSendEvent::UpdateHTLCs { .. } => {},
5036                 _ => panic!("Unexpected event"),
5037         }
5038         match events[1] {
5039                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5040                 _ => panic!("Unexepected event"),
5041         }
5042         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5043         assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
5044         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5045         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5046         assert_eq!(htlc_success_txn[0].input.len(), 1);
5047         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5048         assert_eq!(htlc_success_txn[1].input.len(), 1);
5049         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5050         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5051         assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5052
5053         mine_transaction(&nodes[1], &htlc_timeout_tx);
5054         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5055         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 }]);
5056         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5057         assert!(htlc_updates.update_add_htlcs.is_empty());
5058         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5059         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5060         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5061         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5062         check_added_monitors!(nodes[1], 1);
5063
5064         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5065         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5066         {
5067                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5068         }
5069         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5070
5071         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5072         mine_transaction(&nodes[1], &htlc_success_txn[1]);
5073         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
5074         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5075         assert!(updates.update_add_htlcs.is_empty());
5076         assert!(updates.update_fail_htlcs.is_empty());
5077         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5078         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5079         assert!(updates.update_fail_malformed_htlcs.is_empty());
5080         check_added_monitors!(nodes[1], 1);
5081
5082         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5083         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5084         expect_payment_sent(&nodes[0], our_payment_preimage, None, true, true);
5085 }
5086
5087 #[test]
5088 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5089         let chanmon_cfgs = create_chanmon_cfgs(2);
5090         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5091         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5092         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5093
5094         // Create some initial channels
5095         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5096
5097         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5098         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5099         assert_eq!(local_txn.len(), 1);
5100         assert_eq!(local_txn[0].input.len(), 1);
5101         check_spends!(local_txn[0], chan_1.3);
5102
5103         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5104         nodes[1].node.claim_funds(payment_preimage);
5105         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5106         check_added_monitors!(nodes[1], 1);
5107
5108         mine_transaction(&nodes[1], &local_txn[0]);
5109         check_added_monitors!(nodes[1], 1);
5110         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
5111         let events = nodes[1].node.get_and_clear_pending_msg_events();
5112         match events[0] {
5113                 MessageSendEvent::UpdateHTLCs { .. } => {},
5114                 _ => panic!("Unexpected event"),
5115         }
5116         match events[1] {
5117                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5118                 _ => panic!("Unexepected event"),
5119         }
5120         let node_tx = {
5121                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5122                 assert_eq!(node_txn.len(), 1);
5123                 assert_eq!(node_txn[0].input.len(), 1);
5124                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5125                 check_spends!(node_txn[0], local_txn[0]);
5126                 node_txn[0].clone()
5127         };
5128
5129         mine_transaction(&nodes[1], &node_tx);
5130         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5131
5132         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5133         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5134         assert_eq!(spend_txn.len(), 1);
5135         assert_eq!(spend_txn[0].input.len(), 1);
5136         check_spends!(spend_txn[0], node_tx);
5137         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5138 }
5139
5140 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5141         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5142         // unrevoked commitment transaction.
5143         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5144         // a remote RAA before they could be failed backwards (and combinations thereof).
5145         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5146         // use the same payment hashes.
5147         // Thus, we use a six-node network:
5148         //
5149         // A \         / E
5150         //    - C - D -
5151         // B /         \ F
5152         // And test where C fails back to A/B when D announces its latest commitment transaction
5153         let chanmon_cfgs = create_chanmon_cfgs(6);
5154         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5155         // When this test was written, the default base fee floated based on the HTLC count.
5156         // It is now fixed, so we simply set the fee to the expected value here.
5157         let mut config = test_default_channel_config();
5158         config.channel_config.forwarding_fee_base_msat = 196;
5159         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5160                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5161         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5162
5163         let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
5164         let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5165         let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5166         let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5167         let chan_3_5  = create_announced_chan_between_nodes(&nodes, 3, 5);
5168
5169         // Rebalance and check output sanity...
5170         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5171         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5172         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
5173
5174         let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
5175                 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().context.holder_dust_limit_satoshis;
5176         // 0th HTLC:
5177         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
5178         // 1st HTLC:
5179         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
5180         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5181         // 2nd HTLC:
5182         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
5183         // 3rd HTLC:
5184         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
5185         // 4th HTLC:
5186         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5187         // 5th HTLC:
5188         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5189         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5190         // 6th HTLC:
5191         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());
5192         // 7th HTLC:
5193         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());
5194
5195         // 8th HTLC:
5196         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5197         // 9th HTLC:
5198         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5199         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
5200
5201         // 10th HTLC:
5202         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
5203         // 11th HTLC:
5204         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5205         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());
5206
5207         // Double-check that six of the new HTLC were added
5208         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5209         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5210         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5211         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5212
5213         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5214         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5215         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5216         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5217         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5218         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5219         check_added_monitors!(nodes[4], 0);
5220
5221         let failed_destinations = vec![
5222                 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5223                 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5224                 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5225                 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5226         ];
5227         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5228         check_added_monitors!(nodes[4], 1);
5229
5230         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5231         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5232         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5233         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5234         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5235         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5236
5237         // Fail 3rd below-dust and 7th above-dust HTLCs
5238         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5239         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5240         check_added_monitors!(nodes[5], 0);
5241
5242         let failed_destinations_2 = vec![
5243                 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5244                 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5245         ];
5246         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5247         check_added_monitors!(nodes[5], 1);
5248
5249         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5250         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5251         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5252         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5253
5254         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5255
5256         // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5257         let failed_destinations_3 = vec![
5258                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5259                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5260                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5261                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5262                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5263                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5264         ];
5265         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5266         check_added_monitors!(nodes[3], 1);
5267         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5268         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5269         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5270         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5271         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5272         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5273         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5274         if deliver_last_raa {
5275                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5276         } else {
5277                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5278         }
5279
5280         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5281         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5282         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5283         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5284         //
5285         // We now broadcast the latest commitment transaction, which *should* result in failures for
5286         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5287         // the non-broadcast above-dust HTLCs.
5288         //
5289         // Alternatively, we may broadcast the previous commitment transaction, which should only
5290         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5291         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5292
5293         if announce_latest {
5294                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5295         } else {
5296                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5297         }
5298         let events = nodes[2].node.get_and_clear_pending_events();
5299         let close_event = if deliver_last_raa {
5300                 assert_eq!(events.len(), 2 + 6);
5301                 events.last().clone().unwrap()
5302         } else {
5303                 assert_eq!(events.len(), 1);
5304                 events.last().clone().unwrap()
5305         };
5306         match close_event {
5307                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5308                 _ => panic!("Unexpected event"),
5309         }
5310
5311         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5312         check_closed_broadcast!(nodes[2], true);
5313         if deliver_last_raa {
5314                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5315
5316                 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();
5317                 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5318         } else {
5319                 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5320                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5321                 } else {
5322                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5323                 };
5324
5325                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5326         }
5327         check_added_monitors!(nodes[2], 3);
5328
5329         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5330         assert_eq!(cs_msgs.len(), 2);
5331         let mut a_done = false;
5332         for msg in cs_msgs {
5333                 match msg {
5334                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5335                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5336                                 // should be failed-backwards here.
5337                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5338                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5339                                         for htlc in &updates.update_fail_htlcs {
5340                                                 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 });
5341                                         }
5342                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5343                                         assert!(!a_done);
5344                                         a_done = true;
5345                                         &nodes[0]
5346                                 } else {
5347                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5348                                         for htlc in &updates.update_fail_htlcs {
5349                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5350                                         }
5351                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5352                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5353                                         &nodes[1]
5354                                 };
5355                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5356                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5357                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5358                                 if announce_latest {
5359                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5360                                         if *node_id == nodes[0].node.get_our_node_id() {
5361                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5362                                         }
5363                                 }
5364                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5365                         },
5366                         _ => panic!("Unexpected event"),
5367                 }
5368         }
5369
5370         let as_events = nodes[0].node.get_and_clear_pending_events();
5371         assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5372         let mut as_failds = HashSet::new();
5373         let mut as_updates = 0;
5374         for event in as_events.iter() {
5375                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5376                         assert!(as_failds.insert(*payment_hash));
5377                         if *payment_hash != payment_hash_2 {
5378                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5379                         } else {
5380                                 assert!(!payment_failed_permanently);
5381                         }
5382                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5383                                 as_updates += 1;
5384                         }
5385                 } else if let &Event::PaymentFailed { .. } = event {
5386                 } else { panic!("Unexpected event"); }
5387         }
5388         assert!(as_failds.contains(&payment_hash_1));
5389         assert!(as_failds.contains(&payment_hash_2));
5390         if announce_latest {
5391                 assert!(as_failds.contains(&payment_hash_3));
5392                 assert!(as_failds.contains(&payment_hash_5));
5393         }
5394         assert!(as_failds.contains(&payment_hash_6));
5395
5396         let bs_events = nodes[1].node.get_and_clear_pending_events();
5397         assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5398         let mut bs_failds = HashSet::new();
5399         let mut bs_updates = 0;
5400         for event in bs_events.iter() {
5401                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5402                         assert!(bs_failds.insert(*payment_hash));
5403                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5404                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5405                         } else {
5406                                 assert!(!payment_failed_permanently);
5407                         }
5408                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5409                                 bs_updates += 1;
5410                         }
5411                 } else if let &Event::PaymentFailed { .. } = event {
5412                 } else { panic!("Unexpected event"); }
5413         }
5414         assert!(bs_failds.contains(&payment_hash_1));
5415         assert!(bs_failds.contains(&payment_hash_2));
5416         if announce_latest {
5417                 assert!(bs_failds.contains(&payment_hash_4));
5418         }
5419         assert!(bs_failds.contains(&payment_hash_5));
5420
5421         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5422         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5423         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5424         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5425         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5426         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5427 }
5428
5429 #[test]
5430 fn test_fail_backwards_latest_remote_announce_a() {
5431         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5432 }
5433
5434 #[test]
5435 fn test_fail_backwards_latest_remote_announce_b() {
5436         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5437 }
5438
5439 #[test]
5440 fn test_fail_backwards_previous_remote_announce() {
5441         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5442         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5443         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5444 }
5445
5446 #[test]
5447 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5448         let chanmon_cfgs = create_chanmon_cfgs(2);
5449         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5450         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5451         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5452
5453         // Create some initial channels
5454         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5455
5456         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5457         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5458         assert_eq!(local_txn[0].input.len(), 1);
5459         check_spends!(local_txn[0], chan_1.3);
5460
5461         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5462         mine_transaction(&nodes[0], &local_txn[0]);
5463         check_closed_broadcast!(nodes[0], true);
5464         check_added_monitors!(nodes[0], 1);
5465         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5466         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5467
5468         let htlc_timeout = {
5469                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5470                 assert_eq!(node_txn.len(), 1);
5471                 assert_eq!(node_txn[0].input.len(), 1);
5472                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5473                 check_spends!(node_txn[0], local_txn[0]);
5474                 node_txn[0].clone()
5475         };
5476
5477         mine_transaction(&nodes[0], &htlc_timeout);
5478         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5479         expect_payment_failed!(nodes[0], our_payment_hash, false);
5480
5481         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5482         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5483         assert_eq!(spend_txn.len(), 3);
5484         check_spends!(spend_txn[0], local_txn[0]);
5485         assert_eq!(spend_txn[1].input.len(), 1);
5486         check_spends!(spend_txn[1], htlc_timeout);
5487         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5488         assert_eq!(spend_txn[2].input.len(), 2);
5489         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5490         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5491                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5492 }
5493
5494 #[test]
5495 fn test_key_derivation_params() {
5496         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5497         // manager rotation to test that `channel_keys_id` returned in
5498         // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5499         // then derive a `delayed_payment_key`.
5500
5501         let chanmon_cfgs = create_chanmon_cfgs(3);
5502
5503         // We manually create the node configuration to backup the seed.
5504         let seed = [42; 32];
5505         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5506         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);
5507         let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5508         let scorer = RwLock::new(test_utils::TestScorer::new());
5509         let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5510         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)) };
5511         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5512         node_cfgs.remove(0);
5513         node_cfgs.insert(0, node);
5514
5515         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5516         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5517
5518         // Create some initial channels
5519         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5520         // for node 0
5521         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5522         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5523         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5524
5525         // Ensure all nodes are at the same height
5526         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5527         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5528         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5529         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5530
5531         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5532         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5533         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5534         assert_eq!(local_txn_1[0].input.len(), 1);
5535         check_spends!(local_txn_1[0], chan_1.3);
5536
5537         // We check funding pubkey are unique
5538         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]));
5539         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]));
5540         if from_0_funding_key_0 == from_1_funding_key_0
5541             || from_0_funding_key_0 == from_1_funding_key_1
5542             || from_0_funding_key_1 == from_1_funding_key_0
5543             || from_0_funding_key_1 == from_1_funding_key_1 {
5544                 panic!("Funding pubkeys aren't unique");
5545         }
5546
5547         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5548         mine_transaction(&nodes[0], &local_txn_1[0]);
5549         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5550         check_closed_broadcast!(nodes[0], true);
5551         check_added_monitors!(nodes[0], 1);
5552         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5553
5554         let htlc_timeout = {
5555                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5556                 assert_eq!(node_txn.len(), 1);
5557                 assert_eq!(node_txn[0].input.len(), 1);
5558                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5559                 check_spends!(node_txn[0], local_txn_1[0]);
5560                 node_txn[0].clone()
5561         };
5562
5563         mine_transaction(&nodes[0], &htlc_timeout);
5564         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5565         expect_payment_failed!(nodes[0], our_payment_hash, false);
5566
5567         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5568         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5569         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5570         assert_eq!(spend_txn.len(), 3);
5571         check_spends!(spend_txn[0], local_txn_1[0]);
5572         assert_eq!(spend_txn[1].input.len(), 1);
5573         check_spends!(spend_txn[1], htlc_timeout);
5574         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5575         assert_eq!(spend_txn[2].input.len(), 2);
5576         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5577         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5578                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5579 }
5580
5581 #[test]
5582 fn test_static_output_closing_tx() {
5583         let chanmon_cfgs = create_chanmon_cfgs(2);
5584         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5585         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5586         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5587
5588         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5589
5590         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5591         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5592
5593         mine_transaction(&nodes[0], &closing_tx);
5594         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
5595         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5596
5597         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5598         assert_eq!(spend_txn.len(), 1);
5599         check_spends!(spend_txn[0], closing_tx);
5600
5601         mine_transaction(&nodes[1], &closing_tx);
5602         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
5603         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5604
5605         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5606         assert_eq!(spend_txn.len(), 1);
5607         check_spends!(spend_txn[0], closing_tx);
5608 }
5609
5610 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5611         let chanmon_cfgs = create_chanmon_cfgs(2);
5612         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5613         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5614         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5615         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5616
5617         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5618
5619         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5620         // present in B's local commitment transaction, but none of A's commitment transactions.
5621         nodes[1].node.claim_funds(payment_preimage);
5622         check_added_monitors!(nodes[1], 1);
5623         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5624
5625         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5626         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5627         expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
5628
5629         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5630         check_added_monitors!(nodes[0], 1);
5631         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5632         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5633         check_added_monitors!(nodes[1], 1);
5634
5635         let starting_block = nodes[1].best_block_info();
5636         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5637         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5638                 connect_block(&nodes[1], &block);
5639                 block.header.prev_blockhash = block.block_hash();
5640         }
5641         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5642         check_closed_broadcast!(nodes[1], true);
5643         check_added_monitors!(nodes[1], 1);
5644         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
5645 }
5646
5647 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5648         let chanmon_cfgs = create_chanmon_cfgs(2);
5649         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5650         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5651         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5652         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5653
5654         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5655         nodes[0].node.send_payment_with_route(&route, payment_hash,
5656                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5657         check_added_monitors!(nodes[0], 1);
5658
5659         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5660
5661         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5662         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5663         // to "time out" the HTLC.
5664
5665         let starting_block = nodes[1].best_block_info();
5666         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5667
5668         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5669                 connect_block(&nodes[0], &block);
5670                 block.header.prev_blockhash = block.block_hash();
5671         }
5672         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5673         check_closed_broadcast!(nodes[0], true);
5674         check_added_monitors!(nodes[0], 1);
5675         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5676 }
5677
5678 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5679         let chanmon_cfgs = create_chanmon_cfgs(3);
5680         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5681         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5682         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5683         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5684
5685         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5686         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5687         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5688         // actually revoked.
5689         let htlc_value = if use_dust { 50000 } else { 3000000 };
5690         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5691         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5692         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5693         check_added_monitors!(nodes[1], 1);
5694
5695         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5696         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5697         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5698         check_added_monitors!(nodes[0], 1);
5699         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5700         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5701         check_added_monitors!(nodes[1], 1);
5702         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5703         check_added_monitors!(nodes[1], 1);
5704         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5705
5706         if check_revoke_no_close {
5707                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5708                 check_added_monitors!(nodes[0], 1);
5709         }
5710
5711         let starting_block = nodes[1].best_block_info();
5712         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5713         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5714                 connect_block(&nodes[0], &block);
5715                 block.header.prev_blockhash = block.block_hash();
5716         }
5717         if !check_revoke_no_close {
5718                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5719                 check_closed_broadcast!(nodes[0], true);
5720                 check_added_monitors!(nodes[0], 1);
5721                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5722         } else {
5723                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5724         }
5725 }
5726
5727 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5728 // There are only a few cases to test here:
5729 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5730 //    broadcastable commitment transactions result in channel closure,
5731 //  * its included in an unrevoked-but-previous remote commitment transaction,
5732 //  * its included in the latest remote or local commitment transactions.
5733 // We test each of the three possible commitment transactions individually and use both dust and
5734 // non-dust HTLCs.
5735 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5736 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5737 // tested for at least one of the cases in other tests.
5738 #[test]
5739 fn htlc_claim_single_commitment_only_a() {
5740         do_htlc_claim_local_commitment_only(true);
5741         do_htlc_claim_local_commitment_only(false);
5742
5743         do_htlc_claim_current_remote_commitment_only(true);
5744         do_htlc_claim_current_remote_commitment_only(false);
5745 }
5746
5747 #[test]
5748 fn htlc_claim_single_commitment_only_b() {
5749         do_htlc_claim_previous_remote_commitment_only(true, false);
5750         do_htlc_claim_previous_remote_commitment_only(false, false);
5751         do_htlc_claim_previous_remote_commitment_only(true, true);
5752         do_htlc_claim_previous_remote_commitment_only(false, true);
5753 }
5754
5755 #[test]
5756 #[should_panic]
5757 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5758         let chanmon_cfgs = create_chanmon_cfgs(2);
5759         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5760         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5761         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5762         // Force duplicate randomness for every get-random call
5763         for node in nodes.iter() {
5764                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5765         }
5766
5767         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5768         let channel_value_satoshis=10000;
5769         let push_msat=10001;
5770         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5771         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5772         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5773         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5774
5775         // Create a second channel with the same random values. This used to panic due to a colliding
5776         // channel_id, but now panics due to a colliding outbound SCID alias.
5777         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5778 }
5779
5780 #[test]
5781 fn bolt2_open_channel_sending_node_checks_part2() {
5782         let chanmon_cfgs = create_chanmon_cfgs(2);
5783         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5784         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5785         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5786
5787         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5788         let channel_value_satoshis=2^24;
5789         let push_msat=10001;
5790         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5791
5792         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5793         let channel_value_satoshis=10000;
5794         // Test when push_msat is equal to 1000 * funding_satoshis.
5795         let push_msat=1000*channel_value_satoshis+1;
5796         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5797
5798         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5799         let channel_value_satoshis=10000;
5800         let push_msat=10001;
5801         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
5802         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5803         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5804
5805         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5806         // 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
5807         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5808
5809         // 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.
5810         assert!(BREAKDOWN_TIMEOUT>0);
5811         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5812
5813         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5814         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5815         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5816
5817         // 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.
5818         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5819         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5820         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5821         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5822         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5823 }
5824
5825 #[test]
5826 fn bolt2_open_channel_sane_dust_limit() {
5827         let chanmon_cfgs = create_chanmon_cfgs(2);
5828         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5829         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5830         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5831
5832         let channel_value_satoshis=1000000;
5833         let push_msat=10001;
5834         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5835         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5836         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5837         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5838
5839         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5840         let events = nodes[1].node.get_and_clear_pending_msg_events();
5841         let err_msg = match events[0] {
5842                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5843                         msg.clone()
5844                 },
5845                 _ => panic!("Unexpected event"),
5846         };
5847         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5848 }
5849
5850 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5851 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5852 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5853 // is no longer affordable once it's freed.
5854 #[test]
5855 fn test_fail_holding_cell_htlc_upon_free() {
5856         let chanmon_cfgs = create_chanmon_cfgs(2);
5857         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5858         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5859         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5860         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5861
5862         // First nodes[0] generates an update_fee, setting the channel's
5863         // pending_update_fee.
5864         {
5865                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5866                 *feerate_lock += 20;
5867         }
5868         nodes[0].node.timer_tick_occurred();
5869         check_added_monitors!(nodes[0], 1);
5870
5871         let events = nodes[0].node.get_and_clear_pending_msg_events();
5872         assert_eq!(events.len(), 1);
5873         let (update_msg, commitment_signed) = match events[0] {
5874                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5875                         (update_fee.as_ref(), commitment_signed)
5876                 },
5877                 _ => panic!("Unexpected event"),
5878         };
5879
5880         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5881
5882         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5883         let channel_reserve = chan_stat.channel_reserve_msat;
5884         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5885         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5886
5887         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5888         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
5889         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5890
5891         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5892         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5893                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5894         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5895         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5896
5897         // Flush the pending fee update.
5898         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5899         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5900         check_added_monitors!(nodes[1], 1);
5901         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5902         check_added_monitors!(nodes[0], 1);
5903
5904         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5905         // HTLC, but now that the fee has been raised the payment will now fail, causing
5906         // us to surface its failure to the user.
5907         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5908         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5909         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Freeing holding cell with 1 HTLC updates in channel {}", chan.2), 1);
5910
5911         // Check that the payment failed to be sent out.
5912         let events = nodes[0].node.get_and_clear_pending_events();
5913         assert_eq!(events.len(), 2);
5914         match &events[0] {
5915                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5916                         assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5917                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5918                         assert_eq!(*payment_failed_permanently, false);
5919                         assert_eq!(*short_channel_id, Some(route.paths[0].hops[0].short_channel_id));
5920                 },
5921                 _ => panic!("Unexpected event"),
5922         }
5923         match &events[1] {
5924                 &Event::PaymentFailed { ref payment_hash, .. } => {
5925                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5926                 },
5927                 _ => panic!("Unexpected event"),
5928         }
5929 }
5930
5931 // Test that if multiple HTLCs are released from the holding cell and one is
5932 // valid but the other is no longer valid upon release, the valid HTLC can be
5933 // successfully completed while the other one fails as expected.
5934 #[test]
5935 fn test_free_and_fail_holding_cell_htlcs() {
5936         let chanmon_cfgs = create_chanmon_cfgs(2);
5937         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5938         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5939         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5940         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5941
5942         // First nodes[0] generates an update_fee, setting the channel's
5943         // pending_update_fee.
5944         {
5945                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5946                 *feerate_lock += 200;
5947         }
5948         nodes[0].node.timer_tick_occurred();
5949         check_added_monitors!(nodes[0], 1);
5950
5951         let events = nodes[0].node.get_and_clear_pending_msg_events();
5952         assert_eq!(events.len(), 1);
5953         let (update_msg, commitment_signed) = match events[0] {
5954                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5955                         (update_fee.as_ref(), commitment_signed)
5956                 },
5957                 _ => panic!("Unexpected event"),
5958         };
5959
5960         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5961
5962         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5963         let channel_reserve = chan_stat.channel_reserve_msat;
5964         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5965         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5966
5967         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5968         let amt_1 = 20000;
5969         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features) - amt_1;
5970         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5971         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5972
5973         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5974         nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
5975                 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5976         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5977         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5978         let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5979         nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
5980                 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
5981         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5982         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5983
5984         // Flush the pending fee update.
5985         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5986         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5987         check_added_monitors!(nodes[1], 1);
5988         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5989         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5990         check_added_monitors!(nodes[0], 2);
5991
5992         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5993         // but now that the fee has been raised the second payment will now fail, causing us
5994         // to surface its failure to the user. The first payment should succeed.
5995         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5996         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5997         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Freeing holding cell with 2 HTLC updates in channel {}", chan.2), 1);
5998
5999         // Check that the second payment failed to be sent out.
6000         let events = nodes[0].node.get_and_clear_pending_events();
6001         assert_eq!(events.len(), 2);
6002         match &events[0] {
6003                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
6004                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6005                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6006                         assert_eq!(*payment_failed_permanently, false);
6007                         assert_eq!(*short_channel_id, Some(route_2.paths[0].hops[0].short_channel_id));
6008                 },
6009                 _ => panic!("Unexpected event"),
6010         }
6011         match &events[1] {
6012                 &Event::PaymentFailed { ref payment_hash, .. } => {
6013                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6014                 },
6015                 _ => panic!("Unexpected event"),
6016         }
6017
6018         // Complete the first payment and the RAA from the fee update.
6019         let (payment_event, send_raa_event) = {
6020                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6021                 assert_eq!(msgs.len(), 2);
6022                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6023         };
6024         let raa = match send_raa_event {
6025                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6026                 _ => panic!("Unexpected event"),
6027         };
6028         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6029         check_added_monitors!(nodes[1], 1);
6030         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6031         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6032         let events = nodes[1].node.get_and_clear_pending_events();
6033         assert_eq!(events.len(), 1);
6034         match events[0] {
6035                 Event::PendingHTLCsForwardable { .. } => {},
6036                 _ => panic!("Unexpected event"),
6037         }
6038         nodes[1].node.process_pending_htlc_forwards();
6039         let events = nodes[1].node.get_and_clear_pending_events();
6040         assert_eq!(events.len(), 1);
6041         match events[0] {
6042                 Event::PaymentClaimable { .. } => {},
6043                 _ => panic!("Unexpected event"),
6044         }
6045         nodes[1].node.claim_funds(payment_preimage_1);
6046         check_added_monitors!(nodes[1], 1);
6047         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6048
6049         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6050         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6051         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6052         expect_payment_sent!(nodes[0], payment_preimage_1);
6053 }
6054
6055 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6056 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6057 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6058 // once it's freed.
6059 #[test]
6060 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6061         let chanmon_cfgs = create_chanmon_cfgs(3);
6062         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6063         // Avoid having to include routing fees in calculations
6064         let mut config = test_default_channel_config();
6065         config.channel_config.forwarding_fee_base_msat = 0;
6066         config.channel_config.forwarding_fee_proportional_millionths = 0;
6067         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6068         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6069         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6070         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
6071
6072         // First nodes[1] generates an update_fee, setting the channel's
6073         // pending_update_fee.
6074         {
6075                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6076                 *feerate_lock += 20;
6077         }
6078         nodes[1].node.timer_tick_occurred();
6079         check_added_monitors!(nodes[1], 1);
6080
6081         let events = nodes[1].node.get_and_clear_pending_msg_events();
6082         assert_eq!(events.len(), 1);
6083         let (update_msg, commitment_signed) = match events[0] {
6084                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6085                         (update_fee.as_ref(), commitment_signed)
6086                 },
6087                 _ => panic!("Unexpected event"),
6088         };
6089
6090         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6091
6092         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
6093         let channel_reserve = chan_stat.channel_reserve_msat;
6094         let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
6095         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_0_1.2);
6096
6097         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6098         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6099         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6100         let payment_event = {
6101                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6102                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6103                 check_added_monitors!(nodes[0], 1);
6104
6105                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6106                 assert_eq!(events.len(), 1);
6107
6108                 SendEvent::from_event(events.remove(0))
6109         };
6110         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6111         check_added_monitors!(nodes[1], 0);
6112         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6113         expect_pending_htlcs_forwardable!(nodes[1]);
6114
6115         chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
6116         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6117
6118         // Flush the pending fee update.
6119         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6120         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6121         check_added_monitors!(nodes[2], 1);
6122         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6123         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6124         check_added_monitors!(nodes[1], 2);
6125
6126         // A final RAA message is generated to finalize the fee update.
6127         let events = nodes[1].node.get_and_clear_pending_msg_events();
6128         assert_eq!(events.len(), 1);
6129
6130         let raa_msg = match &events[0] {
6131                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6132                         msg.clone()
6133                 },
6134                 _ => panic!("Unexpected event"),
6135         };
6136
6137         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6138         check_added_monitors!(nodes[2], 1);
6139         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6140
6141         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6142         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6143         assert_eq!(process_htlc_forwards_event.len(), 2);
6144         match &process_htlc_forwards_event[0] {
6145                 &Event::PendingHTLCsForwardable { .. } => {},
6146                 _ => panic!("Unexpected event"),
6147         }
6148
6149         // In response, we call ChannelManager's process_pending_htlc_forwards
6150         nodes[1].node.process_pending_htlc_forwards();
6151         check_added_monitors!(nodes[1], 1);
6152
6153         // This causes the HTLC to be failed backwards.
6154         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6155         assert_eq!(fail_event.len(), 1);
6156         let (fail_msg, commitment_signed) = match &fail_event[0] {
6157                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6158                         assert_eq!(updates.update_add_htlcs.len(), 0);
6159                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6160                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6161                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6162                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6163                 },
6164                 _ => panic!("Unexpected event"),
6165         };
6166
6167         // Pass the failure messages back to nodes[0].
6168         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6169         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6170
6171         // Complete the HTLC failure+removal process.
6172         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6173         check_added_monitors!(nodes[0], 1);
6174         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6175         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6176         check_added_monitors!(nodes[1], 2);
6177         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6178         assert_eq!(final_raa_event.len(), 1);
6179         let raa = match &final_raa_event[0] {
6180                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6181                 _ => panic!("Unexpected event"),
6182         };
6183         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6184         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6185         check_added_monitors!(nodes[0], 1);
6186 }
6187
6188 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6189 // 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.
6190 //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.
6191
6192 #[test]
6193 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6194         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6195         let chanmon_cfgs = create_chanmon_cfgs(2);
6196         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6197         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6198         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6199         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6200
6201         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6202         route.paths[0].hops[0].fee_msat = 100;
6203
6204         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6205                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6206                 ), true, APIError::ChannelUnavailable { .. }, {});
6207         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6208 }
6209
6210 #[test]
6211 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6212         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6213         let chanmon_cfgs = create_chanmon_cfgs(2);
6214         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6215         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6216         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6217         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6218
6219         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6220         route.paths[0].hops[0].fee_msat = 0;
6221         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6222                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6223                 true, APIError::ChannelUnavailable { ref err },
6224                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6225
6226         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6227         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6228 }
6229
6230 #[test]
6231 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6232         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6233         let chanmon_cfgs = create_chanmon_cfgs(2);
6234         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6235         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6236         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6237         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6238
6239         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6240         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6241                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6242         check_added_monitors!(nodes[0], 1);
6243         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6244         updates.update_add_htlcs[0].amount_msat = 0;
6245
6246         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6247         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6248         check_closed_broadcast!(nodes[1], true).unwrap();
6249         check_added_monitors!(nodes[1], 1);
6250         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() },
6251                 [nodes[0].node.get_our_node_id()], 100000);
6252 }
6253
6254 #[test]
6255 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6256         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6257         //It is enforced when constructing a route.
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, 1000000, 0);
6263
6264         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6265                 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
6266         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6267         route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;
6268         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6269                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6270                 ), true, APIError::InvalidRoute { ref err },
6271                 assert_eq!(err, &"Channel CLTV overflowed?"));
6272 }
6273
6274 #[test]
6275 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6276         //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.
6277         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6278         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6279         let chanmon_cfgs = create_chanmon_cfgs(2);
6280         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6281         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6282         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6283         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6284         let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6285                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context.counterparty_max_accepted_htlcs as u64;
6286
6287         // Fetch a route in advance as we will be unable to once we're unable to send.
6288         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6289         for i in 0..max_accepted_htlcs {
6290                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6291                 let payment_event = {
6292                         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6293                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6294                         check_added_monitors!(nodes[0], 1);
6295
6296                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6297                         assert_eq!(events.len(), 1);
6298                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6299                                 assert_eq!(htlcs[0].htlc_id, i);
6300                         } else {
6301                                 assert!(false);
6302                         }
6303                         SendEvent::from_event(events.remove(0))
6304                 };
6305                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6306                 check_added_monitors!(nodes[1], 0);
6307                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6308
6309                 expect_pending_htlcs_forwardable!(nodes[1]);
6310                 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6311         }
6312         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6313                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6314                 ), true, APIError::ChannelUnavailable { .. }, {});
6315
6316         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6317 }
6318
6319 #[test]
6320 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6321         //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.
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         let channel_value = 100000;
6327         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6328         let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6329
6330         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6331
6332         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6333         // Manually create a route over our max in flight (which our router normally automatically
6334         // limits us to.
6335         route.paths[0].hops[0].fee_msat =  max_in_flight + 1;
6336         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6337                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6338                 ), true, APIError::ChannelUnavailable { .. }, {});
6339         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6340
6341         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6342 }
6343
6344 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6345 #[test]
6346 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6347         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
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         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6353         let htlc_minimum_msat: u64;
6354         {
6355                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6356                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6357                 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6358                 htlc_minimum_msat = channel.context.get_holder_htlc_minimum_msat();
6359         }
6360
6361         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6362         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6363                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6364         check_added_monitors!(nodes[0], 1);
6365         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6366         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6367         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6368         assert!(nodes[1].node.list_channels().is_empty());
6369         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6370         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()));
6371         check_added_monitors!(nodes[1], 1);
6372         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6373 }
6374
6375 #[test]
6376 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6377         //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
6378         let chanmon_cfgs = create_chanmon_cfgs(2);
6379         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6380         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6381         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6382         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6383
6384         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6385         let channel_reserve = chan_stat.channel_reserve_msat;
6386         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6387         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
6388         // The 2* and +1 are for the fee spike reserve.
6389         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6390
6391         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6392         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6393         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6394                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6395         check_added_monitors!(nodes[0], 1);
6396         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6397
6398         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6399         // at this time channel-initiatee receivers are not required to enforce that senders
6400         // respect the fee_spike_reserve.
6401         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6402         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6403
6404         assert!(nodes[1].node.list_channels().is_empty());
6405         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6406         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6407         check_added_monitors!(nodes[1], 1);
6408         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6409 }
6410
6411 #[test]
6412 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6413         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6414         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6415         let chanmon_cfgs = create_chanmon_cfgs(2);
6416         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6417         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6418         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6419         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6420
6421         let send_amt = 3999999;
6422         let (mut route, our_payment_hash, _, our_payment_secret) =
6423                 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
6424         route.paths[0].hops[0].fee_msat = send_amt;
6425         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6426         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6427         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6428         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6429                 &route.paths[0], send_amt, RecipientOnionFields::secret_only(our_payment_secret), cur_height, &None).unwrap();
6430         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
6431
6432         let mut msg = msgs::UpdateAddHTLC {
6433                 channel_id: chan.2,
6434                 htlc_id: 0,
6435                 amount_msat: 1000,
6436                 payment_hash: our_payment_hash,
6437                 cltv_expiry: htlc_cltv,
6438                 onion_routing_packet: onion_packet.clone(),
6439                 skimmed_fee_msat: None,
6440         };
6441
6442         for i in 0..50 {
6443                 msg.htlc_id = i as u64;
6444                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6445         }
6446         msg.htlc_id = (50) as u64;
6447         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6448
6449         assert!(nodes[1].node.list_channels().is_empty());
6450         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6451         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6452         check_added_monitors!(nodes[1], 1);
6453         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6454 }
6455
6456 #[test]
6457 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6458         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
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_with_value(&nodes, 0, 1, 1000000, 1000000);
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 mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6470         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;
6471         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6472
6473         assert!(nodes[1].node.list_channels().is_empty());
6474         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6475         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6476         check_added_monitors!(nodes[1], 1);
6477         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 1000000);
6478 }
6479
6480 #[test]
6481 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6482         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6483         let chanmon_cfgs = create_chanmon_cfgs(2);
6484         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6485         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6486         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6487
6488         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6489         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6490         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6491                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6492         check_added_monitors!(nodes[0], 1);
6493         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6494         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6495         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6496
6497         assert!(nodes[1].node.list_channels().is_empty());
6498         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6499         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6500         check_added_monitors!(nodes[1], 1);
6501         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6502 }
6503
6504 #[test]
6505 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6506         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6507         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6508         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6509         let chanmon_cfgs = create_chanmon_cfgs(2);
6510         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6511         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6512         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6513
6514         create_announced_chan_between_nodes(&nodes, 0, 1);
6515         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6516         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6517                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6518         check_added_monitors!(nodes[0], 1);
6519         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6520         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6521
6522         //Disconnect and Reconnect
6523         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6524         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6525         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
6526                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
6527         }, true).unwrap();
6528         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6529         assert_eq!(reestablish_1.len(), 1);
6530         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
6531                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
6532         }, false).unwrap();
6533         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6534         assert_eq!(reestablish_2.len(), 1);
6535         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6536         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6537         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6538         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6539
6540         //Resend HTLC
6541         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6542         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6543         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6544         check_added_monitors!(nodes[1], 1);
6545         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6546
6547         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6548
6549         assert!(nodes[1].node.list_channels().is_empty());
6550         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6551         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6552         check_added_monitors!(nodes[1], 1);
6553         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6554 }
6555
6556 #[test]
6557 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6558         //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.
6559
6560         let chanmon_cfgs = create_chanmon_cfgs(2);
6561         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6562         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6563         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6564         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6565         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6566         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6567                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6568
6569         check_added_monitors!(nodes[0], 1);
6570         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6571         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6572
6573         let update_msg = msgs::UpdateFulfillHTLC{
6574                 channel_id: chan.2,
6575                 htlc_id: 0,
6576                 payment_preimage: our_payment_preimage,
6577         };
6578
6579         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6580
6581         assert!(nodes[0].node.list_channels().is_empty());
6582         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6583         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()));
6584         check_added_monitors!(nodes[0], 1);
6585         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6586 }
6587
6588 #[test]
6589 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6590         //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.
6591
6592         let chanmon_cfgs = create_chanmon_cfgs(2);
6593         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6594         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6595         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6596         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6597
6598         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6599         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6600                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6601         check_added_monitors!(nodes[0], 1);
6602         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6603         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6604
6605         let update_msg = msgs::UpdateFailHTLC{
6606                 channel_id: chan.2,
6607                 htlc_id: 0,
6608                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6609         };
6610
6611         nodes[0].node.handle_update_fail_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!(regex::Regex::new(r"Remote tried to fulfill/fail HTLC \(\d+\) before it had been committed").unwrap().is_match(err_msg.data.as_str()));
6616         check_added_monitors!(nodes[0], 1);
6617         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6618 }
6619
6620 #[test]
6621 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6622         //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.
6623
6624         let chanmon_cfgs = create_chanmon_cfgs(2);
6625         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6626         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6627         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6628         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6629
6630         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6631         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6632                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6633         check_added_monitors!(nodes[0], 1);
6634         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6635         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6636         let update_msg = msgs::UpdateFailMalformedHTLC{
6637                 channel_id: chan.2,
6638                 htlc_id: 0,
6639                 sha256_of_onion: [1; 32],
6640                 failure_code: 0x8000,
6641         };
6642
6643         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6644
6645         assert!(nodes[0].node.list_channels().is_empty());
6646         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6647         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()));
6648         check_added_monitors!(nodes[0], 1);
6649         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6650 }
6651
6652 #[test]
6653 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6654         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6655
6656         let chanmon_cfgs = create_chanmon_cfgs(2);
6657         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6658         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6659         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6660         create_announced_chan_between_nodes(&nodes, 0, 1);
6661
6662         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6663
6664         nodes[1].node.claim_funds(our_payment_preimage);
6665         check_added_monitors!(nodes[1], 1);
6666         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6667
6668         let events = nodes[1].node.get_and_clear_pending_msg_events();
6669         assert_eq!(events.len(), 1);
6670         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6671                 match events[0] {
6672                         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, .. } } => {
6673                                 assert!(update_add_htlcs.is_empty());
6674                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6675                                 assert!(update_fail_htlcs.is_empty());
6676                                 assert!(update_fail_malformed_htlcs.is_empty());
6677                                 assert!(update_fee.is_none());
6678                                 update_fulfill_htlcs[0].clone()
6679                         },
6680                         _ => panic!("Unexpected event"),
6681                 }
6682         };
6683
6684         update_fulfill_msg.htlc_id = 1;
6685
6686         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6687
6688         assert!(nodes[0].node.list_channels().is_empty());
6689         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6690         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6691         check_added_monitors!(nodes[0], 1);
6692         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6693 }
6694
6695 #[test]
6696 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6697         //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.
6698
6699         let chanmon_cfgs = create_chanmon_cfgs(2);
6700         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6701         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6702         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6703         create_announced_chan_between_nodes(&nodes, 0, 1);
6704
6705         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6706
6707         nodes[1].node.claim_funds(our_payment_preimage);
6708         check_added_monitors!(nodes[1], 1);
6709         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6710
6711         let events = nodes[1].node.get_and_clear_pending_msg_events();
6712         assert_eq!(events.len(), 1);
6713         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6714                 match events[0] {
6715                         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, .. } } => {
6716                                 assert!(update_add_htlcs.is_empty());
6717                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6718                                 assert!(update_fail_htlcs.is_empty());
6719                                 assert!(update_fail_malformed_htlcs.is_empty());
6720                                 assert!(update_fee.is_none());
6721                                 update_fulfill_htlcs[0].clone()
6722                         },
6723                         _ => panic!("Unexpected event"),
6724                 }
6725         };
6726
6727         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6728
6729         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6730
6731         assert!(nodes[0].node.list_channels().is_empty());
6732         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6733         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6734         check_added_monitors!(nodes[0], 1);
6735         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6736 }
6737
6738 #[test]
6739 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6740         //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.
6741
6742         let chanmon_cfgs = create_chanmon_cfgs(2);
6743         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6744         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6745         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6746         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6747
6748         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6749         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6750                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6751         check_added_monitors!(nodes[0], 1);
6752
6753         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6754         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6755
6756         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6757         check_added_monitors!(nodes[1], 0);
6758         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6759
6760         let events = nodes[1].node.get_and_clear_pending_msg_events();
6761
6762         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6763                 match events[0] {
6764                         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, .. } } => {
6765                                 assert!(update_add_htlcs.is_empty());
6766                                 assert!(update_fulfill_htlcs.is_empty());
6767                                 assert!(update_fail_htlcs.is_empty());
6768                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6769                                 assert!(update_fee.is_none());
6770                                 update_fail_malformed_htlcs[0].clone()
6771                         },
6772                         _ => panic!("Unexpected event"),
6773                 }
6774         };
6775         update_msg.failure_code &= !0x8000;
6776         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6777
6778         assert!(nodes[0].node.list_channels().is_empty());
6779         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6780         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6781         check_added_monitors!(nodes[0], 1);
6782         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 1000000);
6783 }
6784
6785 #[test]
6786 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6787         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6788         //    * 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.
6789
6790         let chanmon_cfgs = create_chanmon_cfgs(3);
6791         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6792         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6793         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6794         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6795         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6796
6797         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6798
6799         //First hop
6800         let mut payment_event = {
6801                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6802                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6803                 check_added_monitors!(nodes[0], 1);
6804                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6805                 assert_eq!(events.len(), 1);
6806                 SendEvent::from_event(events.remove(0))
6807         };
6808         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6809         check_added_monitors!(nodes[1], 0);
6810         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6811         expect_pending_htlcs_forwardable!(nodes[1]);
6812         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6813         assert_eq!(events_2.len(), 1);
6814         check_added_monitors!(nodes[1], 1);
6815         payment_event = SendEvent::from_event(events_2.remove(0));
6816         assert_eq!(payment_event.msgs.len(), 1);
6817
6818         //Second Hop
6819         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6820         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6821         check_added_monitors!(nodes[2], 0);
6822         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6823
6824         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6825         assert_eq!(events_3.len(), 1);
6826         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6827                 match events_3[0] {
6828                         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 } } => {
6829                                 assert!(update_add_htlcs.is_empty());
6830                                 assert!(update_fulfill_htlcs.is_empty());
6831                                 assert!(update_fail_htlcs.is_empty());
6832                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6833                                 assert!(update_fee.is_none());
6834                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6835                         },
6836                         _ => panic!("Unexpected event"),
6837                 }
6838         };
6839
6840         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6841
6842         check_added_monitors!(nodes[1], 0);
6843         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6844         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 }]);
6845         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6846         assert_eq!(events_4.len(), 1);
6847
6848         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6849         match events_4[0] {
6850                 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, .. } } => {
6851                         assert!(update_add_htlcs.is_empty());
6852                         assert!(update_fulfill_htlcs.is_empty());
6853                         assert_eq!(update_fail_htlcs.len(), 1);
6854                         assert!(update_fail_malformed_htlcs.is_empty());
6855                         assert!(update_fee.is_none());
6856                 },
6857                 _ => panic!("Unexpected event"),
6858         };
6859
6860         check_added_monitors!(nodes[1], 1);
6861 }
6862
6863 #[test]
6864 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6865         let chanmon_cfgs = create_chanmon_cfgs(3);
6866         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6867         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6868         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6869         create_announced_chan_between_nodes(&nodes, 0, 1);
6870         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6871
6872         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6873
6874         // First hop
6875         let mut payment_event = {
6876                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6877                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6878                 check_added_monitors!(nodes[0], 1);
6879                 SendEvent::from_node(&nodes[0])
6880         };
6881
6882         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6883         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6884         expect_pending_htlcs_forwardable!(nodes[1]);
6885         check_added_monitors!(nodes[1], 1);
6886         payment_event = SendEvent::from_node(&nodes[1]);
6887         assert_eq!(payment_event.msgs.len(), 1);
6888
6889         // Second Hop
6890         payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6891         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6892         check_added_monitors!(nodes[2], 0);
6893         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6894
6895         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6896         assert_eq!(events_3.len(), 1);
6897         match events_3[0] {
6898                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6899                         let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6900                         // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6901                         update_msg.failure_code |= 0x2000;
6902
6903                         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6904                         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6905                 },
6906                 _ => panic!("Unexpected event"),
6907         }
6908
6909         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6910                 vec![HTLCDestination::NextHopChannel {
6911                         node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6912         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6913         assert_eq!(events_4.len(), 1);
6914         check_added_monitors!(nodes[1], 1);
6915
6916         match events_4[0] {
6917                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6918                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6919                         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6920                 },
6921                 _ => panic!("Unexpected event"),
6922         }
6923
6924         let events_5 = nodes[0].node.get_and_clear_pending_events();
6925         assert_eq!(events_5.len(), 2);
6926
6927         // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6928         // the node originating the error to its next hop.
6929         match events_5[0] {
6930                 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6931                 } => {
6932                         assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6933                         assert!(is_permanent);
6934                         assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6935                 },
6936                 _ => panic!("Unexpected event"),
6937         }
6938         match events_5[1] {
6939                 Event::PaymentFailed { payment_hash, .. } => {
6940                         assert_eq!(payment_hash, our_payment_hash);
6941                 },
6942                 _ => panic!("Unexpected event"),
6943         }
6944
6945         // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6946 }
6947
6948 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6949         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6950         // 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
6951         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6952
6953         let mut chanmon_cfgs = create_chanmon_cfgs(2);
6954         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6955         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6956         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6957         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6958         let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
6959
6960         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6961                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context.holder_dust_limit_satoshis;
6962
6963         // We route 2 dust-HTLCs between A and B
6964         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6965         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6966         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6967
6968         // Cache one local commitment tx as previous
6969         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6970
6971         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6972         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6973         check_added_monitors!(nodes[1], 0);
6974         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6975         check_added_monitors!(nodes[1], 1);
6976
6977         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6978         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6979         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6980         check_added_monitors!(nodes[0], 1);
6981
6982         // Cache one local commitment tx as lastest
6983         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6984
6985         let events = nodes[0].node.get_and_clear_pending_msg_events();
6986         match events[0] {
6987                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6988                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6989                 },
6990                 _ => panic!("Unexpected event"),
6991         }
6992         match events[1] {
6993                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6994                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6995                 },
6996                 _ => panic!("Unexpected event"),
6997         }
6998
6999         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7000         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7001         if announce_latest {
7002                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7003         } else {
7004                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7005         }
7006
7007         check_closed_broadcast!(nodes[0], true);
7008         check_added_monitors!(nodes[0], 1);
7009         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7010
7011         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7012         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7013         let events = nodes[0].node.get_and_clear_pending_events();
7014         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7015         assert_eq!(events.len(), 4);
7016         let mut first_failed = false;
7017         for event in events {
7018                 match event {
7019                         Event::PaymentPathFailed { payment_hash, .. } => {
7020                                 if payment_hash == payment_hash_1 {
7021                                         assert!(!first_failed);
7022                                         first_failed = true;
7023                                 } else {
7024                                         assert_eq!(payment_hash, payment_hash_2);
7025                                 }
7026                         },
7027                         Event::PaymentFailed { .. } => {}
7028                         _ => panic!("Unexpected event"),
7029                 }
7030         }
7031 }
7032
7033 #[test]
7034 fn test_failure_delay_dust_htlc_local_commitment() {
7035         do_test_failure_delay_dust_htlc_local_commitment(true);
7036         do_test_failure_delay_dust_htlc_local_commitment(false);
7037 }
7038
7039 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7040         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7041         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7042         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7043         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7044         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7045         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7046
7047         let chanmon_cfgs = create_chanmon_cfgs(3);
7048         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7049         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7050         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7051         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
7052
7053         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
7054                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context.holder_dust_limit_satoshis;
7055
7056         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7057         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7058
7059         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7060         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7061
7062         // We revoked bs_commitment_tx
7063         if revoked {
7064                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7065                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7066         }
7067
7068         let mut timeout_tx = Vec::new();
7069         if local {
7070                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7071                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7072                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7073                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7074                 expect_payment_failed!(nodes[0], dust_hash, false);
7075
7076                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7077                 check_closed_broadcast!(nodes[0], true);
7078                 check_added_monitors!(nodes[0], 1);
7079                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7080                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7081                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7082                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7083                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7084                 mine_transaction(&nodes[0], &timeout_tx[0]);
7085                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7086                 expect_payment_failed!(nodes[0], non_dust_hash, false);
7087         } else {
7088                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7089                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7090                 check_closed_broadcast!(nodes[0], true);
7091                 check_added_monitors!(nodes[0], 1);
7092                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7093                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7094
7095                 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7096                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7097                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7098                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7099                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7100                 // dust HTLC should have been failed.
7101                 expect_payment_failed!(nodes[0], dust_hash, false);
7102
7103                 if !revoked {
7104                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7105                 } else {
7106                         assert_eq!(timeout_tx[0].lock_time.0, 11);
7107                 }
7108                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7109                 mine_transaction(&nodes[0], &timeout_tx[0]);
7110                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7111                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7112                 expect_payment_failed!(nodes[0], non_dust_hash, false);
7113         }
7114 }
7115
7116 #[test]
7117 fn test_sweep_outbound_htlc_failure_update() {
7118         do_test_sweep_outbound_htlc_failure_update(false, true);
7119         do_test_sweep_outbound_htlc_failure_update(false, false);
7120         do_test_sweep_outbound_htlc_failure_update(true, false);
7121 }
7122
7123 #[test]
7124 fn test_user_configurable_csv_delay() {
7125         // We test our channel constructors yield errors when we pass them absurd csv delay
7126
7127         let mut low_our_to_self_config = UserConfig::default();
7128         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7129         let mut high_their_to_self_config = UserConfig::default();
7130         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7131         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7132         let chanmon_cfgs = create_chanmon_cfgs(2);
7133         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7134         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7135         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7136
7137         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in OutboundV1Channel::new()
7138         if let Err(error) = OutboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7139                 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
7140                 &low_our_to_self_config, 0, 42)
7141         {
7142                 match error {
7143                         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())); },
7144                         _ => panic!("Unexpected event"),
7145                 }
7146         } else { assert!(false) }
7147
7148         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in InboundV1Channel::new()
7149         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7150         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7151         open_channel.to_self_delay = 200;
7152         if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7153                 &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,
7154                 &low_our_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7155         {
7156                 match error {
7157                         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()));  },
7158                         _ => panic!("Unexpected event"),
7159                 }
7160         } else { assert!(false); }
7161
7162         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7163         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7164         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()));
7165         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7166         accept_channel.to_self_delay = 200;
7167         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
7168         let reason_msg;
7169         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7170                 match action {
7171                         &ErrorAction::SendErrorMessage { ref msg } => {
7172                                 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()));
7173                                 reason_msg = msg.data.clone();
7174                         },
7175                         _ => { panic!(); }
7176                 }
7177         } else { panic!(); }
7178         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg }, [nodes[1].node.get_our_node_id()], 1000000);
7179
7180         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in InboundV1Channel::new()
7181         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7182         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7183         open_channel.to_self_delay = 200;
7184         if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7185                 &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,
7186                 &high_their_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7187         {
7188                 match error {
7189                         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())); },
7190                         _ => panic!("Unexpected event"),
7191                 }
7192         } else { assert!(false); }
7193 }
7194
7195 #[test]
7196 fn test_check_htlc_underpaying() {
7197         // Send payment through A -> B but A is maliciously
7198         // sending a probe payment (i.e less than expected value0
7199         // to B, B should refuse payment.
7200
7201         let chanmon_cfgs = create_chanmon_cfgs(2);
7202         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7203         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7204         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7205
7206         // Create some initial channels
7207         create_announced_chan_between_nodes(&nodes, 0, 1);
7208
7209         let scorer = test_utils::TestScorer::new();
7210         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7211         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(),
7212                 TEST_FINAL_CLTV).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7213         let route_params = RouteParameters::from_payment_params_and_value(payment_params, 10_000);
7214         let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(),
7215                 None, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7216         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7217         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7218         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7219                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7220         check_added_monitors!(nodes[0], 1);
7221
7222         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7223         assert_eq!(events.len(), 1);
7224         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7225         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7226         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7227
7228         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7229         // and then will wait a second random delay before failing the HTLC back:
7230         expect_pending_htlcs_forwardable!(nodes[1]);
7231         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7232
7233         // Node 3 is expecting payment of 100_000 but received 10_000,
7234         // it should fail htlc like we didn't know the preimage.
7235         nodes[1].node.process_pending_htlc_forwards();
7236
7237         let events = nodes[1].node.get_and_clear_pending_msg_events();
7238         assert_eq!(events.len(), 1);
7239         let (update_fail_htlc, commitment_signed) = match events[0] {
7240                 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 } } => {
7241                         assert!(update_add_htlcs.is_empty());
7242                         assert!(update_fulfill_htlcs.is_empty());
7243                         assert_eq!(update_fail_htlcs.len(), 1);
7244                         assert!(update_fail_malformed_htlcs.is_empty());
7245                         assert!(update_fee.is_none());
7246                         (update_fail_htlcs[0].clone(), commitment_signed)
7247                 },
7248                 _ => panic!("Unexpected event"),
7249         };
7250         check_added_monitors!(nodes[1], 1);
7251
7252         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7253         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7254
7255         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7256         let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7257         expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7258         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7259 }
7260
7261 #[test]
7262 fn test_announce_disable_channels() {
7263         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7264         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7265
7266         let chanmon_cfgs = create_chanmon_cfgs(2);
7267         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7268         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7269         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7270
7271         create_announced_chan_between_nodes(&nodes, 0, 1);
7272         create_announced_chan_between_nodes(&nodes, 1, 0);
7273         create_announced_chan_between_nodes(&nodes, 0, 1);
7274
7275         // Disconnect peers
7276         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7277         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7278
7279         for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
7280                 nodes[0].node.timer_tick_occurred();
7281         }
7282         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7283         assert_eq!(msg_events.len(), 3);
7284         let mut chans_disabled = HashMap::new();
7285         for e in msg_events {
7286                 match e {
7287                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7288                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7289                                 // Check that each channel gets updated exactly once
7290                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7291                                         panic!("Generated ChannelUpdate for wrong chan!");
7292                                 }
7293                         },
7294                         _ => panic!("Unexpected event"),
7295                 }
7296         }
7297         // Reconnect peers
7298         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
7299                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
7300         }, true).unwrap();
7301         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7302         assert_eq!(reestablish_1.len(), 3);
7303         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
7304                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
7305         }, false).unwrap();
7306         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7307         assert_eq!(reestablish_2.len(), 3);
7308
7309         // Reestablish chan_1
7310         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7311         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7312         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7313         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7314         // Reestablish chan_2
7315         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7316         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7317         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7318         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7319         // Reestablish chan_3
7320         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7321         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7322         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7323         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7324
7325         for _ in 0..ENABLE_GOSSIP_TICKS {
7326                 nodes[0].node.timer_tick_occurred();
7327         }
7328         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7329         nodes[0].node.timer_tick_occurred();
7330         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7331         assert_eq!(msg_events.len(), 3);
7332         for e in msg_events {
7333                 match e {
7334                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7335                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7336                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7337                                         // Each update should have a higher timestamp than the previous one, replacing
7338                                         // the old one.
7339                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7340                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7341                                 }
7342                         },
7343                         _ => panic!("Unexpected event"),
7344                 }
7345         }
7346         // Check that each channel gets updated exactly once
7347         assert!(chans_disabled.is_empty());
7348 }
7349
7350 #[test]
7351 fn test_bump_penalty_txn_on_revoked_commitment() {
7352         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7353         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7354
7355         let chanmon_cfgs = create_chanmon_cfgs(2);
7356         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7357         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7358         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7359
7360         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7361
7362         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7363         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7364                 .with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7365         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000);
7366         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7367
7368         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7369         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7370         assert_eq!(revoked_txn[0].output.len(), 4);
7371         assert_eq!(revoked_txn[0].input.len(), 1);
7372         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7373         let revoked_txid = revoked_txn[0].txid();
7374
7375         let mut penalty_sum = 0;
7376         for outp in revoked_txn[0].output.iter() {
7377                 if outp.script_pubkey.is_v0_p2wsh() {
7378                         penalty_sum += outp.value;
7379                 }
7380         }
7381
7382         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7383         let header_114 = connect_blocks(&nodes[1], 14);
7384
7385         // Actually revoke tx by claiming a HTLC
7386         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7387         connect_block(&nodes[1], &create_dummy_block(header_114, 42, vec![revoked_txn[0].clone()]));
7388         check_added_monitors!(nodes[1], 1);
7389
7390         // One or more justice tx should have been broadcast, check it
7391         let penalty_1;
7392         let feerate_1;
7393         {
7394                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7395                 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7396                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7397                 assert_eq!(node_txn[0].output.len(), 1);
7398                 check_spends!(node_txn[0], revoked_txn[0]);
7399                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7400                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7401                 penalty_1 = node_txn[0].txid();
7402                 node_txn.clear();
7403         };
7404
7405         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7406         connect_blocks(&nodes[1], 15);
7407         let mut penalty_2 = penalty_1;
7408         let mut feerate_2 = 0;
7409         {
7410                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7411                 assert_eq!(node_txn.len(), 1);
7412                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7413                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7414                         assert_eq!(node_txn[0].output.len(), 1);
7415                         check_spends!(node_txn[0], revoked_txn[0]);
7416                         penalty_2 = node_txn[0].txid();
7417                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7418                         assert_ne!(penalty_2, penalty_1);
7419                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7420                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7421                         // Verify 25% bump heuristic
7422                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7423                         node_txn.clear();
7424                 }
7425         }
7426         assert_ne!(feerate_2, 0);
7427
7428         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7429         connect_blocks(&nodes[1], 1);
7430         let penalty_3;
7431         let mut feerate_3 = 0;
7432         {
7433                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7434                 assert_eq!(node_txn.len(), 1);
7435                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7436                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7437                         assert_eq!(node_txn[0].output.len(), 1);
7438                         check_spends!(node_txn[0], revoked_txn[0]);
7439                         penalty_3 = node_txn[0].txid();
7440                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7441                         assert_ne!(penalty_3, penalty_2);
7442                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7443                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7444                         // Verify 25% bump heuristic
7445                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7446                         node_txn.clear();
7447                 }
7448         }
7449         assert_ne!(feerate_3, 0);
7450
7451         nodes[1].node.get_and_clear_pending_events();
7452         nodes[1].node.get_and_clear_pending_msg_events();
7453 }
7454
7455 #[test]
7456 fn test_bump_penalty_txn_on_revoked_htlcs() {
7457         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7458         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7459
7460         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7461         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7462         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7463         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7464         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7465
7466         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7467         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7468         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7469         let scorer = test_utils::TestScorer::new();
7470         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7471         let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7472         let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(), None,
7473                 nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7474         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7475         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7476         let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7477         let route = get_route(&nodes[1].node.get_our_node_id(), &route_params, &nodes[1].network_graph.read_only(), None,
7478                 nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7479         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7480
7481         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7482         assert_eq!(revoked_local_txn[0].input.len(), 1);
7483         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7484
7485         // Revoke local commitment tx
7486         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7487
7488         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7489         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone()]));
7490         check_closed_broadcast!(nodes[1], true);
7491         check_added_monitors!(nodes[1], 1);
7492         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 1000000);
7493         connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7494
7495         let revoked_htlc_txn = {
7496                 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7497                 assert_eq!(txn.len(), 2);
7498
7499                 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7500                 assert_eq!(txn[0].input.len(), 1);
7501                 check_spends!(txn[0], revoked_local_txn[0]);
7502
7503                 assert_eq!(txn[1].input.len(), 1);
7504                 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7505                 assert_eq!(txn[1].output.len(), 1);
7506                 check_spends!(txn[1], revoked_local_txn[0]);
7507
7508                 txn
7509         };
7510
7511         // Broadcast set of revoked txn on A
7512         let hash_128 = connect_blocks(&nodes[0], 40);
7513         let block_11 = create_dummy_block(hash_128, 42, vec![revoked_local_txn[0].clone()]);
7514         connect_block(&nodes[0], &block_11);
7515         let block_129 = create_dummy_block(block_11.block_hash(), 42, vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()]);
7516         connect_block(&nodes[0], &block_129);
7517         let events = nodes[0].node.get_and_clear_pending_events();
7518         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7519         match events.last().unwrap() {
7520                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7521                 _ => panic!("Unexpected event"),
7522         }
7523         let first;
7524         let feerate_1;
7525         let penalty_txn;
7526         {
7527                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7528                 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7529                 // Verify claim tx are spending revoked HTLC txn
7530
7531                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7532                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7533                 // which are included in the same block (they are broadcasted because we scan the
7534                 // transactions linearly and generate claims as we go, they likely should be removed in the
7535                 // future).
7536                 assert_eq!(node_txn[0].input.len(), 1);
7537                 check_spends!(node_txn[0], revoked_local_txn[0]);
7538                 assert_eq!(node_txn[1].input.len(), 1);
7539                 check_spends!(node_txn[1], revoked_local_txn[0]);
7540                 assert_eq!(node_txn[2].input.len(), 1);
7541                 check_spends!(node_txn[2], revoked_local_txn[0]);
7542
7543                 // Each of the three justice transactions claim a separate (single) output of the three
7544                 // available, which we check here:
7545                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7546                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7547                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7548
7549                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7550                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7551
7552                 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7553                 // output, checked above).
7554                 assert_eq!(node_txn[3].input.len(), 2);
7555                 assert_eq!(node_txn[3].output.len(), 1);
7556                 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7557
7558                 first = node_txn[3].txid();
7559                 // Store both feerates for later comparison
7560                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7561                 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7562                 penalty_txn = vec![node_txn[2].clone()];
7563                 node_txn.clear();
7564         }
7565
7566         // Connect one more block to see if bumped penalty are issued for HTLC txn
7567         let block_130 = create_dummy_block(block_129.block_hash(), 42, penalty_txn);
7568         connect_block(&nodes[0], &block_130);
7569         let block_131 = create_dummy_block(block_130.block_hash(), 42, Vec::new());
7570         connect_block(&nodes[0], &block_131);
7571
7572         // Few more blocks to confirm penalty txn
7573         connect_blocks(&nodes[0], 4);
7574         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7575         let header_144 = connect_blocks(&nodes[0], 9);
7576         let node_txn = {
7577                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7578                 assert_eq!(node_txn.len(), 1);
7579
7580                 assert_eq!(node_txn[0].input.len(), 2);
7581                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7582                 // Verify bumped tx is different and 25% bump heuristic
7583                 assert_ne!(first, node_txn[0].txid());
7584                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7585                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7586                 assert!(feerate_2 * 100 > feerate_1 * 125);
7587                 let txn = vec![node_txn[0].clone()];
7588                 node_txn.clear();
7589                 txn
7590         };
7591         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7592         connect_block(&nodes[0], &create_dummy_block(header_144, 42, node_txn));
7593         connect_blocks(&nodes[0], 20);
7594         {
7595                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7596                 // We verify than no new transaction has been broadcast because previously
7597                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7598                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7599                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7600                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7601                 // up bumped justice generation.
7602                 assert_eq!(node_txn.len(), 0);
7603                 node_txn.clear();
7604         }
7605         check_closed_broadcast!(nodes[0], true);
7606         check_added_monitors!(nodes[0], 1);
7607 }
7608
7609 #[test]
7610 fn test_bump_penalty_txn_on_remote_commitment() {
7611         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7612         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7613
7614         // Create 2 HTLCs
7615         // Provide preimage for one
7616         // Check aggregation
7617
7618         let chanmon_cfgs = create_chanmon_cfgs(2);
7619         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7620         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7621         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7622
7623         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7624         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7625         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7626
7627         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7628         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7629         assert_eq!(remote_txn[0].output.len(), 4);
7630         assert_eq!(remote_txn[0].input.len(), 1);
7631         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7632
7633         // Claim a HTLC without revocation (provide B monitor with preimage)
7634         nodes[1].node.claim_funds(payment_preimage);
7635         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7636         mine_transaction(&nodes[1], &remote_txn[0]);
7637         check_added_monitors!(nodes[1], 2);
7638         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7639
7640         // One or more claim tx should have been broadcast, check it
7641         let timeout;
7642         let preimage;
7643         let preimage_bump;
7644         let feerate_timeout;
7645         let feerate_preimage;
7646         {
7647                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7648                 // 3 transactions including:
7649                 //   preimage and timeout sweeps from remote commitment + preimage sweep bump
7650                 assert_eq!(node_txn.len(), 3);
7651                 assert_eq!(node_txn[0].input.len(), 1);
7652                 assert_eq!(node_txn[1].input.len(), 1);
7653                 assert_eq!(node_txn[2].input.len(), 1);
7654                 check_spends!(node_txn[0], remote_txn[0]);
7655                 check_spends!(node_txn[1], remote_txn[0]);
7656                 check_spends!(node_txn[2], remote_txn[0]);
7657
7658                 preimage = node_txn[0].txid();
7659                 let index = node_txn[0].input[0].previous_output.vout;
7660                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7661                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7662
7663                 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7664                         (node_txn[2].clone(), node_txn[1].clone())
7665                 } else {
7666                         (node_txn[1].clone(), node_txn[2].clone())
7667                 };
7668
7669                 preimage_bump = preimage_bump_tx;
7670                 check_spends!(preimage_bump, remote_txn[0]);
7671                 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7672
7673                 timeout = timeout_tx.txid();
7674                 let index = timeout_tx.input[0].previous_output.vout;
7675                 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7676                 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7677
7678                 node_txn.clear();
7679         };
7680         assert_ne!(feerate_timeout, 0);
7681         assert_ne!(feerate_preimage, 0);
7682
7683         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7684         connect_blocks(&nodes[1], 1);
7685         {
7686                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7687                 assert_eq!(node_txn.len(), 1);
7688                 assert_eq!(node_txn[0].input.len(), 1);
7689                 assert_eq!(preimage_bump.input.len(), 1);
7690                 check_spends!(node_txn[0], remote_txn[0]);
7691                 check_spends!(preimage_bump, remote_txn[0]);
7692
7693                 let index = preimage_bump.input[0].previous_output.vout;
7694                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7695                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7696                 assert!(new_feerate * 100 > feerate_timeout * 125);
7697                 assert_ne!(timeout, preimage_bump.txid());
7698
7699                 let index = node_txn[0].input[0].previous_output.vout;
7700                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7701                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7702                 assert!(new_feerate * 100 > feerate_preimage * 125);
7703                 assert_ne!(preimage, node_txn[0].txid());
7704
7705                 node_txn.clear();
7706         }
7707
7708         nodes[1].node.get_and_clear_pending_events();
7709         nodes[1].node.get_and_clear_pending_msg_events();
7710 }
7711
7712 #[test]
7713 fn test_counterparty_raa_skip_no_crash() {
7714         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7715         // commitment transaction, we would have happily carried on and provided them the next
7716         // commitment transaction based on one RAA forward. This would probably eventually have led to
7717         // channel closure, but it would not have resulted in funds loss. Still, our
7718         // TestChannelSigner would have panicked as it doesn't like jumps into the future. Here, we
7719         // check simply that the channel is closed in response to such an RAA, but don't check whether
7720         // we decide to punish our counterparty for revoking their funds (as we don't currently
7721         // implement that).
7722         let chanmon_cfgs = create_chanmon_cfgs(2);
7723         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7724         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7725         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7726         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7727
7728         let per_commitment_secret;
7729         let next_per_commitment_point;
7730         {
7731                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7732                 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7733                 let keys = guard.channel_by_id.get_mut(&channel_id).unwrap().get_signer();
7734
7735                 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7736
7737                 // Make signer believe we got a counterparty signature, so that it allows the revocation
7738                 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7739                 per_commitment_secret = keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7740
7741                 // Must revoke without gaps
7742                 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7743                 keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7744
7745                 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7746                 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7747                         &SecretKey::from_slice(&keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7748         }
7749
7750         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7751                 &msgs::RevokeAndACK {
7752                         channel_id,
7753                         per_commitment_secret,
7754                         next_per_commitment_point,
7755                         #[cfg(taproot)]
7756                         next_local_nonce: None,
7757                 });
7758         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7759         check_added_monitors!(nodes[1], 1);
7760         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() }
7761                 , [nodes[0].node.get_our_node_id()], 100000);
7762 }
7763
7764 #[test]
7765 fn test_bump_txn_sanitize_tracking_maps() {
7766         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7767         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7768
7769         let chanmon_cfgs = create_chanmon_cfgs(2);
7770         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7771         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7772         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7773
7774         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7775         // Lock HTLC in both directions
7776         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7777         let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7778
7779         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7780         assert_eq!(revoked_local_txn[0].input.len(), 1);
7781         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7782
7783         // Revoke local commitment tx
7784         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7785
7786         // Broadcast set of revoked txn on A
7787         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7788         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7789         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7790
7791         mine_transaction(&nodes[0], &revoked_local_txn[0]);
7792         check_closed_broadcast!(nodes[0], true);
7793         check_added_monitors!(nodes[0], 1);
7794         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 1000000);
7795         let penalty_txn = {
7796                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7797                 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7798                 check_spends!(node_txn[0], revoked_local_txn[0]);
7799                 check_spends!(node_txn[1], revoked_local_txn[0]);
7800                 check_spends!(node_txn[2], revoked_local_txn[0]);
7801                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7802                 node_txn.clear();
7803                 penalty_txn
7804         };
7805         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, penalty_txn));
7806         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7807         {
7808                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7809                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7810                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7811         }
7812 }
7813
7814 #[test]
7815 fn test_channel_conf_timeout() {
7816         // Tests that, for inbound channels, we give up on them if the funding transaction does not
7817         // confirm within 2016 blocks, as recommended by BOLT 2.
7818         let chanmon_cfgs = create_chanmon_cfgs(2);
7819         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7820         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7821         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7822
7823         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7824
7825         // The outbound node should wait forever for confirmation:
7826         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7827         // copied here instead of directly referencing the constant.
7828         connect_blocks(&nodes[0], 2016);
7829         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7830
7831         // The inbound node should fail the channel after exactly 2016 blocks
7832         connect_blocks(&nodes[1], 2015);
7833         check_added_monitors!(nodes[1], 0);
7834         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7835
7836         connect_blocks(&nodes[1], 1);
7837         check_added_monitors!(nodes[1], 1);
7838         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut, [nodes[0].node.get_our_node_id()], 1000000);
7839         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7840         assert_eq!(close_ev.len(), 1);
7841         match close_ev[0] {
7842                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7843                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7844                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7845                 },
7846                 _ => panic!("Unexpected event"),
7847         }
7848 }
7849
7850 #[test]
7851 fn test_override_channel_config() {
7852         let chanmon_cfgs = create_chanmon_cfgs(2);
7853         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7854         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7855         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7856
7857         // Node0 initiates a channel to node1 using the override config.
7858         let mut override_config = UserConfig::default();
7859         override_config.channel_handshake_config.our_to_self_delay = 200;
7860
7861         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7862
7863         // Assert the channel created by node0 is using the override config.
7864         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7865         assert_eq!(res.channel_flags, 0);
7866         assert_eq!(res.to_self_delay, 200);
7867 }
7868
7869 #[test]
7870 fn test_override_0msat_htlc_minimum() {
7871         let mut zero_config = UserConfig::default();
7872         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7873         let chanmon_cfgs = create_chanmon_cfgs(2);
7874         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7875         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7876         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7877
7878         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7879         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7880         assert_eq!(res.htlc_minimum_msat, 1);
7881
7882         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7883         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7884         assert_eq!(res.htlc_minimum_msat, 1);
7885 }
7886
7887 #[test]
7888 fn test_channel_update_has_correct_htlc_maximum_msat() {
7889         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7890         // Bolt 7 specifies that if present `htlc_maximum_msat`:
7891         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7892         // 90% of the `channel_value`.
7893         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7894
7895         let mut config_30_percent = UserConfig::default();
7896         config_30_percent.channel_handshake_config.announced_channel = true;
7897         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7898         let mut config_50_percent = UserConfig::default();
7899         config_50_percent.channel_handshake_config.announced_channel = true;
7900         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7901         let mut config_95_percent = UserConfig::default();
7902         config_95_percent.channel_handshake_config.announced_channel = true;
7903         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7904         let mut config_100_percent = UserConfig::default();
7905         config_100_percent.channel_handshake_config.announced_channel = true;
7906         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7907
7908         let chanmon_cfgs = create_chanmon_cfgs(4);
7909         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7910         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)]);
7911         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7912
7913         let channel_value_satoshis = 100000;
7914         let channel_value_msat = channel_value_satoshis * 1000;
7915         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7916         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7917         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7918
7919         let (node_0_chan_update, node_1_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7920         let (node_2_chan_update, node_3_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7921
7922         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7923         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7924         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7925         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7926         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7927         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7928
7929         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7930         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7931         // `channel_value`.
7932         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7933         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7934         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7935         // `channel_value`.
7936         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7937 }
7938
7939 #[test]
7940 fn test_manually_accept_inbound_channel_request() {
7941         let mut manually_accept_conf = UserConfig::default();
7942         manually_accept_conf.manually_accept_inbound_channels = true;
7943         let chanmon_cfgs = create_chanmon_cfgs(2);
7944         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7945         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7946         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7947
7948         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7949         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7950
7951         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7952
7953         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7954         // accepting the inbound channel request.
7955         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7956
7957         let events = nodes[1].node.get_and_clear_pending_events();
7958         match events[0] {
7959                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7960                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7961                 }
7962                 _ => panic!("Unexpected event"),
7963         }
7964
7965         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7966         assert_eq!(accept_msg_ev.len(), 1);
7967
7968         match accept_msg_ev[0] {
7969                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7970                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7971                 }
7972                 _ => panic!("Unexpected event"),
7973         }
7974
7975         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7976
7977         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7978         assert_eq!(close_msg_ev.len(), 1);
7979
7980         let events = nodes[1].node.get_and_clear_pending_events();
7981         match events[0] {
7982                 Event::ChannelClosed { user_channel_id, .. } => {
7983                         assert_eq!(user_channel_id, 23);
7984                 }
7985                 _ => panic!("Unexpected event"),
7986         }
7987 }
7988
7989 #[test]
7990 fn test_manually_reject_inbound_channel_request() {
7991         let mut manually_accept_conf = UserConfig::default();
7992         manually_accept_conf.manually_accept_inbound_channels = true;
7993         let chanmon_cfgs = create_chanmon_cfgs(2);
7994         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7995         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7996         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7997
7998         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7999         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8000
8001         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8002
8003         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8004         // rejecting the inbound channel request.
8005         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8006
8007         let events = nodes[1].node.get_and_clear_pending_events();
8008         match events[0] {
8009                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8010                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8011                 }
8012                 _ => panic!("Unexpected event"),
8013         }
8014
8015         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8016         assert_eq!(close_msg_ev.len(), 1);
8017
8018         match close_msg_ev[0] {
8019                 MessageSendEvent::HandleError { ref node_id, .. } => {
8020                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8021                 }
8022                 _ => panic!("Unexpected event"),
8023         }
8024
8025         // There should be no more events to process, as the channel was never opened.
8026         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8027 }
8028
8029 #[test]
8030 fn test_can_not_accept_inbound_channel_twice() {
8031         let mut manually_accept_conf = UserConfig::default();
8032         manually_accept_conf.manually_accept_inbound_channels = true;
8033         let chanmon_cfgs = create_chanmon_cfgs(2);
8034         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8035         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8036         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8037
8038         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8039         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8040
8041         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8042
8043         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8044         // accepting the inbound channel request.
8045         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8046
8047         let events = nodes[1].node.get_and_clear_pending_events();
8048         match events[0] {
8049                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8050                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8051                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8052                         match api_res {
8053                                 Err(APIError::APIMisuseError { err }) => {
8054                                         assert_eq!(err, "No such channel awaiting to be accepted.");
8055                                 },
8056                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8057                                 Err(e) => panic!("Unexpected Error {:?}", e),
8058                         }
8059                 }
8060                 _ => panic!("Unexpected event"),
8061         }
8062
8063         // Ensure that the channel wasn't closed after attempting to accept it twice.
8064         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8065         assert_eq!(accept_msg_ev.len(), 1);
8066
8067         match accept_msg_ev[0] {
8068                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8069                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8070                 }
8071                 _ => panic!("Unexpected event"),
8072         }
8073 }
8074
8075 #[test]
8076 fn test_can_not_accept_unknown_inbound_channel() {
8077         let chanmon_cfg = create_chanmon_cfgs(2);
8078         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8079         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8080         let nodes = create_network(2, &node_cfg, &node_chanmgr);
8081
8082         let unknown_channel_id = ChannelId::new_zero();
8083         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8084         match api_res {
8085                 Err(APIError::APIMisuseError { err }) => {
8086                         assert_eq!(err, "No such channel awaiting to be accepted.");
8087                 },
8088                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8089                 Err(e) => panic!("Unexpected Error: {:?}", e),
8090         }
8091 }
8092
8093 #[test]
8094 fn test_onion_value_mpp_set_calculation() {
8095         // Test that we use the onion value `amt_to_forward` when
8096         // calculating whether we've reached the `total_msat` of an MPP
8097         // by having a routing node forward more than `amt_to_forward`
8098         // and checking that the receiving node doesn't generate
8099         // a PaymentClaimable event too early
8100         let node_count = 4;
8101         let chanmon_cfgs = create_chanmon_cfgs(node_count);
8102         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8103         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8104         let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8105
8106         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8107         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8108         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8109         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8110
8111         let total_msat = 100_000;
8112         let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
8113         let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
8114         let sample_path = route.paths.pop().unwrap();
8115
8116         let mut path_1 = sample_path.clone();
8117         path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
8118         path_1.hops[0].short_channel_id = chan_1_id;
8119         path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
8120         path_1.hops[1].short_channel_id = chan_3_id;
8121         path_1.hops[1].fee_msat = 100_000;
8122         route.paths.push(path_1);
8123
8124         let mut path_2 = sample_path.clone();
8125         path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
8126         path_2.hops[0].short_channel_id = chan_2_id;
8127         path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
8128         path_2.hops[1].short_channel_id = chan_4_id;
8129         path_2.hops[1].fee_msat = 1_000;
8130         route.paths.push(path_2);
8131
8132         // Send payment
8133         let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
8134         let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
8135                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8136         nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
8137                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8138         check_added_monitors!(nodes[0], expected_paths.len());
8139
8140         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8141         assert_eq!(events.len(), expected_paths.len());
8142
8143         // First path
8144         let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8145         let mut payment_event = SendEvent::from_event(ev);
8146         let mut prev_node = &nodes[0];
8147
8148         for (idx, &node) in expected_paths[0].iter().enumerate() {
8149                 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8150
8151                 if idx == 0 { // routing node
8152                         let session_priv = [3; 32];
8153                         let height = nodes[0].best_block_info().1;
8154                         let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8155                         let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8156                         let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8157                                 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8158                         // Edit amt_to_forward to simulate the sender having set
8159                         // the final amount and the routing node taking less fee
8160                         if let msgs::OutboundOnionPayload::Receive { ref mut amt_msat, .. } = onion_payloads[1] {
8161                                 *amt_msat = 99_000;
8162                         } else { panic!() }
8163                         let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
8164                         payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8165                 }
8166
8167                 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8168                 check_added_monitors!(node, 0);
8169                 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8170                 expect_pending_htlcs_forwardable!(node);
8171
8172                 if idx == 0 {
8173                         let mut events_2 = node.node.get_and_clear_pending_msg_events();
8174                         assert_eq!(events_2.len(), 1);
8175                         check_added_monitors!(node, 1);
8176                         payment_event = SendEvent::from_event(events_2.remove(0));
8177                         assert_eq!(payment_event.msgs.len(), 1);
8178                 } else {
8179                         let events_2 = node.node.get_and_clear_pending_events();
8180                         assert!(events_2.is_empty());
8181                 }
8182
8183                 prev_node = node;
8184         }
8185
8186         // Second path
8187         let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8188         pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8189
8190         claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8191 }
8192
8193 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8194
8195         let routing_node_count = msat_amounts.len();
8196         let node_count = routing_node_count + 2;
8197
8198         let chanmon_cfgs = create_chanmon_cfgs(node_count);
8199         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8200         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8201         let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8202
8203         let src_idx = 0;
8204         let dst_idx = 1;
8205
8206         // Create channels for each amount
8207         let mut expected_paths = Vec::with_capacity(routing_node_count);
8208         let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8209         let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8210         for i in 0..routing_node_count {
8211                 let routing_node = 2 + i;
8212                 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8213                 src_chan_ids.push(src_chan_id);
8214                 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8215                 dst_chan_ids.push(dst_chan_id);
8216                 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8217                 expected_paths.push(path);
8218         }
8219         let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8220
8221         // Create a route for each amount
8222         let example_amount = 100000;
8223         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);
8224         let sample_path = route.paths.pop().unwrap();
8225         for i in 0..routing_node_count {
8226                 let routing_node = 2 + i;
8227                 let mut path = sample_path.clone();
8228                 path.hops[0].pubkey = nodes[routing_node].node.get_our_node_id();
8229                 path.hops[0].short_channel_id = src_chan_ids[i];
8230                 path.hops[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8231                 path.hops[1].short_channel_id = dst_chan_ids[i];
8232                 path.hops[1].fee_msat = msat_amounts[i];
8233                 route.paths.push(path);
8234         }
8235
8236         // Send payment with manually set total_msat
8237         let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8238         let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8239                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8240         nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8241                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8242         check_added_monitors!(nodes[src_idx], expected_paths.len());
8243
8244         let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8245         assert_eq!(events.len(), expected_paths.len());
8246         let mut amount_received = 0;
8247         for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8248                 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8249
8250                 let current_path_amount = msat_amounts[path_idx];
8251                 amount_received += current_path_amount;
8252                 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8253                 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8254         }
8255
8256         claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8257 }
8258
8259 #[test]
8260 fn test_overshoot_mpp() {
8261         do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8262         do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8263 }
8264
8265 #[test]
8266 fn test_simple_mpp() {
8267         // Simple test of sending a multi-path payment.
8268         let chanmon_cfgs = create_chanmon_cfgs(4);
8269         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8270         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8271         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8272
8273         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8274         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8275         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8276         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8277
8278         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8279         let path = route.paths[0].clone();
8280         route.paths.push(path);
8281         route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
8282         route.paths[0].hops[0].short_channel_id = chan_1_id;
8283         route.paths[0].hops[1].short_channel_id = chan_3_id;
8284         route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
8285         route.paths[1].hops[0].short_channel_id = chan_2_id;
8286         route.paths[1].hops[1].short_channel_id = chan_4_id;
8287         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8288         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8289 }
8290
8291 #[test]
8292 fn test_preimage_storage() {
8293         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8294         let chanmon_cfgs = create_chanmon_cfgs(2);
8295         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8296         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8297         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8298
8299         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8300
8301         {
8302                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8303                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8304                 nodes[0].node.send_payment_with_route(&route, payment_hash,
8305                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8306                 check_added_monitors!(nodes[0], 1);
8307                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8308                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8309                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8310                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8311         }
8312         // Note that after leaving the above scope we have no knowledge of any arguments or return
8313         // values from previous calls.
8314         expect_pending_htlcs_forwardable!(nodes[1]);
8315         let events = nodes[1].node.get_and_clear_pending_events();
8316         assert_eq!(events.len(), 1);
8317         match events[0] {
8318                 Event::PaymentClaimable { ref purpose, .. } => {
8319                         match &purpose {
8320                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8321                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8322                                 },
8323                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8324                         }
8325                 },
8326                 _ => panic!("Unexpected event"),
8327         }
8328 }
8329
8330 #[test]
8331 fn test_bad_secret_hash() {
8332         // Simple test of unregistered payment hash/invalid payment secret handling
8333         let chanmon_cfgs = create_chanmon_cfgs(2);
8334         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8335         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8336         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8337
8338         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8339
8340         let random_payment_hash = PaymentHash([42; 32]);
8341         let random_payment_secret = PaymentSecret([43; 32]);
8342         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8343         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8344
8345         // All the below cases should end up being handled exactly identically, so we macro the
8346         // resulting events.
8347         macro_rules! handle_unknown_invalid_payment_data {
8348                 ($payment_hash: expr) => {
8349                         check_added_monitors!(nodes[0], 1);
8350                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8351                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8352                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8353                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8354
8355                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8356                         // again to process the pending backwards-failure of the HTLC
8357                         expect_pending_htlcs_forwardable!(nodes[1]);
8358                         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8359                         check_added_monitors!(nodes[1], 1);
8360
8361                         // We should fail the payment back
8362                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8363                         match events.pop().unwrap() {
8364                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8365                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8366                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8367                                 },
8368                                 _ => panic!("Unexpected event"),
8369                         }
8370                 }
8371         }
8372
8373         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8374         // Error data is the HTLC value (100,000) and current block height
8375         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8376
8377         // Send a payment with the right payment hash but the wrong payment secret
8378         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8379                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8380         handle_unknown_invalid_payment_data!(our_payment_hash);
8381         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8382
8383         // Send a payment with a random payment hash, but the right payment secret
8384         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8385                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8386         handle_unknown_invalid_payment_data!(random_payment_hash);
8387         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8388
8389         // Send a payment with a random payment hash and random payment secret
8390         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8391                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8392         handle_unknown_invalid_payment_data!(random_payment_hash);
8393         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8394 }
8395
8396 #[test]
8397 fn test_update_err_monitor_lockdown() {
8398         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8399         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8400         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8401         // error.
8402         //
8403         // This scenario may happen in a watchtower setup, where watchtower process a block height
8404         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8405         // commitment at same time.
8406
8407         let chanmon_cfgs = create_chanmon_cfgs(2);
8408         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8409         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8410         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8411
8412         // Create some initial channel
8413         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8414         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8415
8416         // Rebalance the network to generate htlc in the two directions
8417         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8418
8419         // Route a HTLC from node 0 to node 1 (but don't settle)
8420         let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8421
8422         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8423         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8424         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8425         let persister = test_utils::TestPersister::new();
8426         let watchtower = {
8427                 let new_monitor = {
8428                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8429                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8430                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8431                         assert!(new_monitor == *monitor);
8432                         new_monitor
8433                 };
8434                 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);
8435                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8436                 watchtower
8437         };
8438         let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8439         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8440         // transaction lock time requirements here.
8441         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8442         watchtower.chain_monitor.block_connected(&block, 200);
8443
8444         // Try to update ChannelMonitor
8445         nodes[1].node.claim_funds(preimage);
8446         check_added_monitors!(nodes[1], 1);
8447         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8448
8449         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8450         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8451         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8452         {
8453                 let mut node_0_per_peer_lock;
8454                 let mut node_0_peer_state_lock;
8455                 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8456                 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8457                         assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8458                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8459                 } else { assert!(false); }
8460         }
8461         // Our local monitor is in-sync and hasn't processed yet timeout
8462         check_added_monitors!(nodes[0], 1);
8463         let events = nodes[0].node.get_and_clear_pending_events();
8464         assert_eq!(events.len(), 1);
8465 }
8466
8467 #[test]
8468 fn test_concurrent_monitor_claim() {
8469         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8470         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8471         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8472         // state N+1 confirms. Alice claims output from state N+1.
8473
8474         let chanmon_cfgs = create_chanmon_cfgs(2);
8475         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8476         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8477         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8478
8479         // Create some initial channel
8480         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8481         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8482
8483         // Rebalance the network to generate htlc in the two directions
8484         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8485
8486         // Route a HTLC from node 0 to node 1 (but don't settle)
8487         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8488
8489         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8490         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8491         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8492         let persister = test_utils::TestPersister::new();
8493         let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8494                 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8495         );
8496         let watchtower_alice = {
8497                 let new_monitor = {
8498                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8499                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8500                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8501                         assert!(new_monitor == *monitor);
8502                         new_monitor
8503                 };
8504                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &alice_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8505                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8506                 watchtower
8507         };
8508         let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8509         // Make Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8510         // requirements here.
8511         const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8512         alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8513         watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8514
8515         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8516         let alice_state = {
8517                 let mut txn = alice_broadcaster.txn_broadcast();
8518                 assert_eq!(txn.len(), 2);
8519                 txn.remove(0)
8520         };
8521
8522         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8523         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8524         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8525         let persister = test_utils::TestPersister::new();
8526         let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8527         let watchtower_bob = {
8528                 let new_monitor = {
8529                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8530                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8531                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8532                         assert!(new_monitor == *monitor);
8533                         new_monitor
8534                 };
8535                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8536                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8537                 watchtower
8538         };
8539         watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST - 1);
8540
8541         // Route another payment to generate another update with still previous HTLC pending
8542         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8543         nodes[1].node.send_payment_with_route(&route, payment_hash,
8544                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8545         check_added_monitors!(nodes[1], 1);
8546
8547         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8548         assert_eq!(updates.update_add_htlcs.len(), 1);
8549         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8550         {
8551                 let mut node_0_per_peer_lock;
8552                 let mut node_0_peer_state_lock;
8553                 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8554                 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8555                         // Watchtower Alice should already have seen the block and reject the update
8556                         assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8557                         assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8558                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8559                 } else { assert!(false); }
8560         }
8561         // Our local monitor is in-sync and hasn't processed yet timeout
8562         check_added_monitors!(nodes[0], 1);
8563
8564         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8565         watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST);
8566
8567         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8568         let bob_state_y;
8569         {
8570                 let mut txn = bob_broadcaster.txn_broadcast();
8571                 assert_eq!(txn.len(), 2);
8572                 bob_state_y = txn.remove(0);
8573         };
8574
8575         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
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                 [nodes[1].node.get_our_node_id()], 100000);
8581         watchtower_alice.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, vec![bob_state_y.clone()]), height);
8582         check_added_monitors(&nodes[0], 1);
8583         {
8584                 let htlc_txn = alice_broadcaster.txn_broadcast();
8585                 assert_eq!(htlc_txn.len(), 2);
8586                 check_spends!(htlc_txn[0], bob_state_y);
8587                 // Alice doesn't clean up the old HTLC claim since it hasn't seen a conflicting spend for
8588                 // it. However, she should, because it now has an invalid parent.
8589                 check_spends!(htlc_txn[1], alice_state);
8590         }
8591 }
8592
8593 #[test]
8594 fn test_pre_lockin_no_chan_closed_update() {
8595         // Test that if a peer closes a channel in response to a funding_created message we don't
8596         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8597         // message).
8598         //
8599         // Doing so would imply a channel monitor update before the initial channel monitor
8600         // registration, violating our API guarantees.
8601         //
8602         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8603         // then opening a second channel with the same funding output as the first (which is not
8604         // rejected because the first channel does not exist in the ChannelManager) and closing it
8605         // before receiving funding_signed.
8606         let chanmon_cfgs = create_chanmon_cfgs(2);
8607         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8608         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8609         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8610
8611         // Create an initial channel
8612         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8613         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8614         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8615         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8616         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8617
8618         // Move the first channel through the funding flow...
8619         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8620
8621         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8622         check_added_monitors!(nodes[0], 0);
8623
8624         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8625         let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8626         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8627         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8628         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true,
8629                 [nodes[1].node.get_our_node_id(); 2], 100000);
8630 }
8631
8632 #[test]
8633 fn test_htlc_no_detection() {
8634         // This test is a mutation to underscore the detection logic bug we had
8635         // before #653. HTLC value routed is above the remaining balance, thus
8636         // inverting HTLC and `to_remote` output. HTLC will come second and
8637         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8638         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8639         // outputs order detection for correct spending children filtring.
8640
8641         let chanmon_cfgs = create_chanmon_cfgs(2);
8642         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8643         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8644         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8645
8646         // Create some initial channels
8647         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8648
8649         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8650         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8651         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8652         assert_eq!(local_txn[0].input.len(), 1);
8653         assert_eq!(local_txn[0].output.len(), 3);
8654         check_spends!(local_txn[0], chan_1.3);
8655
8656         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8657         let block = create_dummy_block(nodes[0].best_block_hash(), 42, vec![local_txn[0].clone()]);
8658         connect_block(&nodes[0], &block);
8659         // We deliberately connect the local tx twice as this should provoke a failure calling
8660         // this test before #653 fix.
8661         chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &block, nodes[0].best_block_info().1 + 1);
8662         check_closed_broadcast!(nodes[0], true);
8663         check_added_monitors!(nodes[0], 1);
8664         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
8665         connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8666
8667         let htlc_timeout = {
8668                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8669                 assert_eq!(node_txn.len(), 1);
8670                 assert_eq!(node_txn[0].input.len(), 1);
8671                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8672                 check_spends!(node_txn[0], local_txn[0]);
8673                 node_txn[0].clone()
8674         };
8675
8676         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![htlc_timeout.clone()]));
8677         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8678         expect_payment_failed!(nodes[0], our_payment_hash, false);
8679 }
8680
8681 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8682         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8683         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8684         // Carol, Alice would be the upstream node, and Carol the downstream.)
8685         //
8686         // Steps of the test:
8687         // 1) Alice sends a HTLC to Carol through Bob.
8688         // 2) Carol doesn't settle the HTLC.
8689         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8690         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8691         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8692         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8693         // 5) Carol release the preimage to Bob off-chain.
8694         // 6) Bob claims the offered output on the broadcasted commitment.
8695         let chanmon_cfgs = create_chanmon_cfgs(3);
8696         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8697         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8698         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8699
8700         // Create some initial channels
8701         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8702         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8703
8704         // Steps (1) and (2):
8705         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8706         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8707
8708         // Check that Alice's commitment transaction now contains an output for this HTLC.
8709         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8710         check_spends!(alice_txn[0], chan_ab.3);
8711         assert_eq!(alice_txn[0].output.len(), 2);
8712         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8713         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8714         assert_eq!(alice_txn.len(), 2);
8715
8716         // Steps (3) and (4):
8717         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8718         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8719         let mut force_closing_node = 0; // Alice force-closes
8720         let mut counterparty_node = 1; // Bob if Alice force-closes
8721
8722         // Bob force-closes
8723         if !broadcast_alice {
8724                 force_closing_node = 1;
8725                 counterparty_node = 0;
8726         }
8727         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8728         check_closed_broadcast!(nodes[force_closing_node], true);
8729         check_added_monitors!(nodes[force_closing_node], 1);
8730         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed, [nodes[counterparty_node].node.get_our_node_id()], 100000);
8731         if go_onchain_before_fulfill {
8732                 let txn_to_broadcast = match broadcast_alice {
8733                         true => alice_txn.clone(),
8734                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8735                 };
8736                 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, 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, [nodes[0].node.get_our_node_id()], 100000);
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                 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8816                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8817                 if broadcast_alice {
8818                         check_closed_broadcast!(nodes[1], true);
8819                         check_added_monitors!(nodes[1], 1);
8820                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8821                 }
8822                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8823                 if broadcast_alice {
8824                         assert_eq!(bob_txn.len(), 1);
8825                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8826                 } else {
8827                         assert_eq!(bob_txn.len(), 2);
8828                         check_spends!(bob_txn[0], chan_ab.3);
8829                 }
8830         }
8831
8832         // Step (6):
8833         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8834         // broadcasted commitment transaction.
8835         {
8836                 let script_weight = match broadcast_alice {
8837                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8838                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8839                 };
8840                 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8841                 // Bob force-closed and broadcasts the commitment transaction along with a
8842                 // HTLC-output-claiming transaction.
8843                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8844                 if broadcast_alice {
8845                         assert_eq!(bob_txn.len(), 1);
8846                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8847                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8848                 } else {
8849                         assert_eq!(bob_txn.len(), 2);
8850                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8851                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8852                 }
8853         }
8854 }
8855
8856 #[test]
8857 fn test_onchain_htlc_settlement_after_close() {
8858         do_test_onchain_htlc_settlement_after_close(true, true);
8859         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8860         do_test_onchain_htlc_settlement_after_close(true, false);
8861         do_test_onchain_htlc_settlement_after_close(false, false);
8862 }
8863
8864 #[test]
8865 fn test_duplicate_temporary_channel_id_from_different_peers() {
8866         // Tests that we can accept two different `OpenChannel` requests with the same
8867         // `temporary_channel_id`, as long as they are from different peers.
8868         let chanmon_cfgs = create_chanmon_cfgs(3);
8869         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8870         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8871         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8872
8873         // Create an first channel channel
8874         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8875         let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8876
8877         // Create an second channel
8878         nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8879         let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8880
8881         // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8882         // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8883         open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8884
8885         // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8886         // `temporary_channel_id` as they are from different peers.
8887         nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8888         {
8889                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8890                 assert_eq!(events.len(), 1);
8891                 match &events[0] {
8892                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8893                                 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8894                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8895                         },
8896                         _ => panic!("Unexpected event"),
8897                 }
8898         }
8899
8900         nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8901         {
8902                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8903                 assert_eq!(events.len(), 1);
8904                 match &events[0] {
8905                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8906                                 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8907                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8908                         },
8909                         _ => panic!("Unexpected event"),
8910                 }
8911         }
8912 }
8913
8914 #[test]
8915 fn test_duplicate_chan_id() {
8916         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8917         // already open we reject it and keep the old channel.
8918         //
8919         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8920         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8921         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8922         // updating logic for the existing channel.
8923         let chanmon_cfgs = create_chanmon_cfgs(2);
8924         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8925         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8926         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8927
8928         // Create an initial channel
8929         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8930         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8931         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8932         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()));
8933
8934         // Try to create a second channel with the same temporary_channel_id as the first and check
8935         // that it is rejected.
8936         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8937         {
8938                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8939                 assert_eq!(events.len(), 1);
8940                 match events[0] {
8941                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8942                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8943                                 // first (valid) and second (invalid) channels are closed, given they both have
8944                                 // the same non-temporary channel_id. However, currently we do not, so we just
8945                                 // move forward with it.
8946                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8947                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8948                         },
8949                         _ => panic!("Unexpected event"),
8950                 }
8951         }
8952
8953         // Move the first channel through the funding flow...
8954         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8955
8956         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8957         check_added_monitors!(nodes[0], 0);
8958
8959         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8960         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8961         {
8962                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8963                 assert_eq!(added_monitors.len(), 1);
8964                 assert_eq!(added_monitors[0].0, funding_output);
8965                 added_monitors.clear();
8966         }
8967         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
8968
8969         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8970
8971         let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8972         let channel_id = funding_outpoint.to_channel_id();
8973
8974         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8975         // temporary one).
8976
8977         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8978         // Technically this is allowed by the spec, but we don't support it and there's little reason
8979         // to. Still, it shouldn't cause any other issues.
8980         open_chan_msg.temporary_channel_id = channel_id;
8981         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8982         {
8983                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8984                 assert_eq!(events.len(), 1);
8985                 match events[0] {
8986                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8987                                 // Technically, at this point, nodes[1] would be justified in thinking both
8988                                 // channels are closed, but currently we do not, so we just move forward with it.
8989                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8990                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8991                         },
8992                         _ => panic!("Unexpected event"),
8993                 }
8994         }
8995
8996         // Now try to create a second channel which has a duplicate funding output.
8997         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8998         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8999         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
9000         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()));
9001         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9002
9003         let (_, funding_created) = {
9004                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9005                 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9006                 // Once we call `get_funding_created` the channel has a duplicate channel_id as
9007                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9008                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9009                 // channelmanager in a possibly nonsense state instead).
9010                 let mut as_chan = a_peer_state.outbound_v1_channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
9011                 let logger = test_utils::TestLogger::new();
9012                 as_chan.get_funding_created(tx.clone(), funding_outpoint, &&logger).map_err(|_| ()).unwrap()
9013         };
9014         check_added_monitors!(nodes[0], 0);
9015         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9016         // At this point we'll look up if the channel_id is present and immediately fail the channel
9017         // without trying to persist the `ChannelMonitor`.
9018         check_added_monitors!(nodes[1], 0);
9019
9020         // ...still, nodes[1] will reject the duplicate channel.
9021         {
9022                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9023                 assert_eq!(events.len(), 1);
9024                 match events[0] {
9025                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9026                                 // Technically, at this point, nodes[1] would be justified in thinking both
9027                                 // channels are closed, but currently we do not, so we just move forward with it.
9028                                 assert_eq!(msg.channel_id, channel_id);
9029                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9030                         },
9031                         _ => panic!("Unexpected event"),
9032                 }
9033         }
9034
9035         // finally, finish creating the original channel and send a payment over it to make sure
9036         // everything is functional.
9037         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9038         {
9039                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9040                 assert_eq!(added_monitors.len(), 1);
9041                 assert_eq!(added_monitors[0].0, funding_output);
9042                 added_monitors.clear();
9043         }
9044         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9045
9046         let events_4 = nodes[0].node.get_and_clear_pending_events();
9047         assert_eq!(events_4.len(), 0);
9048         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9049         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9050
9051         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9052         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9053         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9054
9055         send_payment(&nodes[0], &[&nodes[1]], 8000000);
9056 }
9057
9058 #[test]
9059 fn test_error_chans_closed() {
9060         // Test that we properly handle error messages, closing appropriate channels.
9061         //
9062         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9063         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9064         // we can test various edge cases around it to ensure we don't regress.
9065         let chanmon_cfgs = create_chanmon_cfgs(3);
9066         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9067         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9068         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9069
9070         // Create some initial channels
9071         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9072         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9073         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
9074
9075         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9076         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9077         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9078
9079         // Closing a channel from a different peer has no effect
9080         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9081         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9082
9083         // Closing one channel doesn't impact others
9084         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9085         check_added_monitors!(nodes[0], 1);
9086         check_closed_broadcast!(nodes[0], false);
9087         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9088                 [nodes[1].node.get_our_node_id()], 100000);
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: ChannelId::new_zero(), 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                 [nodes[1].node.get_our_node_id(); 2], 100000);
9100         let events = nodes[0].node.get_and_clear_pending_msg_events();
9101         assert_eq!(events.len(), 2);
9102         match events[0] {
9103                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9104                         assert_eq!(msg.contents.flags & 2, 2);
9105                 },
9106                 _ => panic!("Unexpected event"),
9107         }
9108         match events[1] {
9109                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9110                         assert_eq!(msg.contents.flags & 2, 2);
9111                 },
9112                 _ => panic!("Unexpected event"),
9113         }
9114         // Note that at this point users of a standard PeerHandler will end up calling
9115         // peer_disconnected.
9116         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9117         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9118
9119         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9120         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9121         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9122 }
9123
9124 #[test]
9125 fn test_invalid_funding_tx() {
9126         // Test that we properly handle invalid funding transactions sent to us from a peer.
9127         //
9128         // Previously, all other major lightning implementations had failed to properly sanitize
9129         // funding transactions from their counterparties, leading to a multi-implementation critical
9130         // security vulnerability (though we always sanitized properly, we've previously had
9131         // un-released crashes in the sanitization process).
9132         //
9133         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9134         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9135         // gave up on it. We test this here by generating such a transaction.
9136         let chanmon_cfgs = create_chanmon_cfgs(2);
9137         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9138         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9139         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9140
9141         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9142         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()));
9143         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()));
9144
9145         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9146
9147         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9148         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9149         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9150         // its length.
9151         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9152         let wit_program_script: Script = wit_program.into();
9153         for output in tx.output.iter_mut() {
9154                 // Make the confirmed funding transaction have a bogus script_pubkey
9155                 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9156         }
9157
9158         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9159         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()));
9160         check_added_monitors!(nodes[1], 1);
9161         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9162
9163         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()));
9164         check_added_monitors!(nodes[0], 1);
9165         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9166
9167         let events_1 = nodes[0].node.get_and_clear_pending_events();
9168         assert_eq!(events_1.len(), 0);
9169
9170         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9171         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9172         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9173
9174         let expected_err = "funding tx had wrong script/value or output index";
9175         confirm_transaction_at(&nodes[1], &tx, 1);
9176         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() },
9177                 [nodes[0].node.get_our_node_id()], 100000);
9178         check_added_monitors!(nodes[1], 1);
9179         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9180         assert_eq!(events_2.len(), 1);
9181         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9182                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9183                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9184                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9185                 } else { panic!(); }
9186         } else { panic!(); }
9187         assert_eq!(nodes[1].node.list_channels().len(), 0);
9188
9189         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9190         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9191         // as its not 32 bytes long.
9192         let mut spend_tx = Transaction {
9193                 version: 2i32, lock_time: PackedLockTime::ZERO,
9194                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9195                         previous_output: BitcoinOutPoint {
9196                                 txid: tx.txid(),
9197                                 vout: idx as u32,
9198                         },
9199                         script_sig: Script::new(),
9200                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9201                         witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9202                 }).collect(),
9203                 output: vec![TxOut {
9204                         value: 1000,
9205                         script_pubkey: Script::new(),
9206                 }]
9207         };
9208         check_spends!(spend_tx, tx);
9209         mine_transaction(&nodes[1], &spend_tx);
9210 }
9211
9212 #[test]
9213 fn test_coinbase_funding_tx() {
9214         // Miners are able to fund channels directly from coinbase transactions, however
9215         // by consensus rules, outputs of a coinbase transaction are encumbered by a 100
9216         // block maturity timelock. To ensure that a (non-0conf) channel like this is enforceable
9217         // on-chain, the minimum depth is updated to 100 blocks for coinbase funding transactions.
9218         //
9219         // Note that 0conf channels with coinbase funding transactions are unaffected and are
9220         // immediately operational after opening.
9221         let chanmon_cfgs = create_chanmon_cfgs(2);
9222         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9223         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9224         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9225
9226         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9227         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9228
9229         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9230         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9231
9232         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9233
9234         // Create the coinbase funding transaction.
9235         let (temporary_channel_id, tx, _) = create_coinbase_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9236
9237         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9238         check_added_monitors!(nodes[0], 0);
9239         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9240
9241         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9242         check_added_monitors!(nodes[1], 1);
9243         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9244
9245         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9246
9247         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
9248         check_added_monitors!(nodes[0], 1);
9249
9250         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9251         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
9252
9253         // Starting at height 0, we "confirm" the coinbase at height 1.
9254         confirm_transaction_at(&nodes[0], &tx, 1);
9255         // We connect 98 more blocks to have 99 confirmations for the coinbase transaction.
9256         connect_blocks(&nodes[0], COINBASE_MATURITY - 2);
9257         // Check that we have no pending message events (we have not queued a `channel_ready` yet).
9258         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
9259         // Now connect one more block which results in 100 confirmations of the coinbase transaction.
9260         connect_blocks(&nodes[0], 1);
9261         // There should now be a `channel_ready` which can be handled.
9262         let _ = &nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &get_event_msg!(&nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id()));
9263
9264         confirm_transaction_at(&nodes[1], &tx, 1);
9265         connect_blocks(&nodes[1], COINBASE_MATURITY - 2);
9266         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9267         connect_blocks(&nodes[1], 1);
9268         expect_channel_ready_event(&nodes[1], &nodes[0].node.get_our_node_id());
9269         create_chan_between_nodes_with_value_confirm_second(&nodes[0], &nodes[1]);
9270 }
9271
9272 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9273         // In the first version of the chain::Confirm interface, after a refactor was made to not
9274         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9275         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9276         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9277         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9278         // spending transaction until height N+1 (or greater). This was due to the way
9279         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9280         // spending transaction at the height the input transaction was confirmed at, not whether we
9281         // should broadcast a spending transaction at the current height.
9282         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9283         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9284         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9285         // until we learned about an additional block.
9286         //
9287         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9288         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9289         let chanmon_cfgs = create_chanmon_cfgs(3);
9290         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9291         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9292         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9293         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9294
9295         create_announced_chan_between_nodes(&nodes, 0, 1);
9296         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9297         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9298         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9299         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9300
9301         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9302         check_closed_broadcast!(nodes[1], true);
9303         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
9304         check_added_monitors!(nodes[1], 1);
9305         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9306         assert_eq!(node_txn.len(), 1);
9307
9308         let conf_height = nodes[1].best_block_info().1;
9309         if !test_height_before_timelock {
9310                 connect_blocks(&nodes[1], 24 * 6);
9311         }
9312         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9313                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9314         if test_height_before_timelock {
9315                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9316                 // generate any events or broadcast any transactions
9317                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9318                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9319         } else {
9320                 // We should broadcast an HTLC transaction spending our funding transaction first
9321                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9322                 assert_eq!(spending_txn.len(), 2);
9323                 assert_eq!(spending_txn[0].txid(), node_txn[0].txid());
9324                 check_spends!(spending_txn[1], node_txn[0]);
9325                 // We should also generate a SpendableOutputs event with the to_self output (as its
9326                 // timelock is up).
9327                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9328                 assert_eq!(descriptor_spend_txn.len(), 1);
9329
9330                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9331                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9332                 // additional block built on top of the current chain.
9333                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9334                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9335                 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 }]);
9336                 check_added_monitors!(nodes[1], 1);
9337
9338                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9339                 assert!(updates.update_add_htlcs.is_empty());
9340                 assert!(updates.update_fulfill_htlcs.is_empty());
9341                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9342                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9343                 assert!(updates.update_fee.is_none());
9344                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9345                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9346                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9347         }
9348 }
9349
9350 #[test]
9351 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9352         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9353         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9354 }
9355
9356 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9357         let chanmon_cfgs = create_chanmon_cfgs(2);
9358         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9359         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9360         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9361
9362         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9363
9364         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9365                 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
9366         let route = get_route!(nodes[0], payment_params, 10_000).unwrap();
9367
9368         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9369
9370         {
9371                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9372                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9373                 check_added_monitors!(nodes[0], 1);
9374                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9375                 assert_eq!(events.len(), 1);
9376                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9377                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9378                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9379         }
9380         expect_pending_htlcs_forwardable!(nodes[1]);
9381         expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9382
9383         {
9384                 // Note that we use a different PaymentId here to allow us to duplicativly pay
9385                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9386                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9387                 check_added_monitors!(nodes[0], 1);
9388                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9389                 assert_eq!(events.len(), 1);
9390                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9391                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9392                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9393                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9394                 // assume the second is a privacy attack (no longer particularly relevant
9395                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9396                 // the first HTLC delivered above.
9397         }
9398
9399         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9400         nodes[1].node.process_pending_htlc_forwards();
9401
9402         if test_for_second_fail_panic {
9403                 // Now we go fail back the first HTLC from the user end.
9404                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9405
9406                 let expected_destinations = vec![
9407                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9408                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9409                 ];
9410                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],  expected_destinations);
9411                 nodes[1].node.process_pending_htlc_forwards();
9412
9413                 check_added_monitors!(nodes[1], 1);
9414                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9415                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9416
9417                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9418                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9419                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9420
9421                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9422                 assert_eq!(failure_events.len(), 4);
9423                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9424                 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9425                 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9426                 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9427         } else {
9428                 // Let the second HTLC fail and claim the first
9429                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9430                 nodes[1].node.process_pending_htlc_forwards();
9431
9432                 check_added_monitors!(nodes[1], 1);
9433                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9434                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9435                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9436
9437                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9438
9439                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9440         }
9441 }
9442
9443 #[test]
9444 fn test_dup_htlc_second_fail_panic() {
9445         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9446         // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9447         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9448         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9449         do_test_dup_htlc_second_rejected(true);
9450 }
9451
9452 #[test]
9453 fn test_dup_htlc_second_rejected() {
9454         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9455         // simply reject the second HTLC but are still able to claim the first HTLC.
9456         do_test_dup_htlc_second_rejected(false);
9457 }
9458
9459 #[test]
9460 fn test_inconsistent_mpp_params() {
9461         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9462         // such HTLC and allow the second to stay.
9463         let chanmon_cfgs = create_chanmon_cfgs(4);
9464         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9465         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9466         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9467
9468         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9469         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9470         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9471         let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9472
9473         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9474                 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
9475         let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
9476         assert_eq!(route.paths.len(), 2);
9477         route.paths.sort_by(|path_a, _| {
9478                 // Sort the path so that the path through nodes[1] comes first
9479                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9480                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9481         });
9482
9483         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9484
9485         let cur_height = nodes[0].best_block_info().1;
9486         let payment_id = PaymentId([42; 32]);
9487
9488         let session_privs = {
9489                 // We create a fake route here so that we start with three pending HTLCs, which we'll
9490                 // ultimately have, just not right away.
9491                 let mut dup_route = route.clone();
9492                 dup_route.paths.push(route.paths[1].clone());
9493                 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9494                         RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9495         };
9496         nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9497                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9498                 &None, session_privs[0]).unwrap();
9499         check_added_monitors!(nodes[0], 1);
9500
9501         {
9502                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9503                 assert_eq!(events.len(), 1);
9504                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9505         }
9506         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9507
9508         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9509                 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9510         check_added_monitors!(nodes[0], 1);
9511
9512         {
9513                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9514                 assert_eq!(events.len(), 1);
9515                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9516
9517                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9518                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9519
9520                 expect_pending_htlcs_forwardable!(nodes[2]);
9521                 check_added_monitors!(nodes[2], 1);
9522
9523                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9524                 assert_eq!(events.len(), 1);
9525                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9526
9527                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9528                 check_added_monitors!(nodes[3], 0);
9529                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9530
9531                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9532                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9533                 // post-payment_secrets) and fail back the new HTLC.
9534         }
9535         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9536         nodes[3].node.process_pending_htlc_forwards();
9537         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9538         nodes[3].node.process_pending_htlc_forwards();
9539
9540         check_added_monitors!(nodes[3], 1);
9541
9542         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9543         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9544         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9545
9546         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 }]);
9547         check_added_monitors!(nodes[2], 1);
9548
9549         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9550         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9551         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9552
9553         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9554
9555         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9556                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9557                 &None, session_privs[2]).unwrap();
9558         check_added_monitors!(nodes[0], 1);
9559
9560         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9561         assert_eq!(events.len(), 1);
9562         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9563
9564         do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9565         expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true, true);
9566 }
9567
9568 #[test]
9569 fn test_double_partial_claim() {
9570         // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9571         // time out, the sender resends only some of the MPP parts, then the user processes the
9572         // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9573         // amount.
9574         let chanmon_cfgs = create_chanmon_cfgs(4);
9575         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9576         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9577         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9578
9579         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9580         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9581         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9582         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9583
9584         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9585         assert_eq!(route.paths.len(), 2);
9586         route.paths.sort_by(|path_a, _| {
9587                 // Sort the path so that the path through nodes[1] comes first
9588                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9589                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9590         });
9591
9592         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9593         // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9594         // amount of time to respond to.
9595
9596         // Connect some blocks to time out the payment
9597         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9598         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9599
9600         let failed_destinations = vec![
9601                 HTLCDestination::FailedPayment { payment_hash },
9602                 HTLCDestination::FailedPayment { payment_hash },
9603         ];
9604         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9605
9606         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9607
9608         // nodes[1] now retries one of the two paths...
9609         nodes[0].node.send_payment_with_route(&route, payment_hash,
9610                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9611         check_added_monitors!(nodes[0], 2);
9612
9613         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9614         assert_eq!(events.len(), 2);
9615         let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9616         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9617
9618         // At this point nodes[3] has received one half of the payment, and the user goes to handle
9619         // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9620         nodes[3].node.claim_funds(payment_preimage);
9621         check_added_monitors!(nodes[3], 0);
9622         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9623 }
9624
9625 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9626 #[derive(Clone, Copy, PartialEq)]
9627 enum ExposureEvent {
9628         /// Breach occurs at HTLC forwarding (see `send_htlc`)
9629         AtHTLCForward,
9630         /// Breach occurs at HTLC reception (see `update_add_htlc`)
9631         AtHTLCReception,
9632         /// Breach occurs at outbound update_fee (see `send_update_fee`)
9633         AtUpdateFeeOutbound,
9634 }
9635
9636 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool, multiplier_dust_limit: bool) {
9637         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9638         // policy.
9639         //
9640         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9641         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9642         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9643         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9644         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9645         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9646         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9647         // might be available again for HTLC processing once the dust bandwidth has cleared up.
9648
9649         let chanmon_cfgs = create_chanmon_cfgs(2);
9650         let mut config = test_default_channel_config();
9651         config.channel_config.max_dust_htlc_exposure = if multiplier_dust_limit {
9652                 // Default test fee estimator rate is 253 sat/kw, so we set the multiplier to 5_000_000 / 253
9653                 // to get roughly the same initial value as the default setting when this test was
9654                 // originally written.
9655                 MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253)
9656         } else { MaxDustHTLCExposure::FixedLimitMsat(5_000_000) }; // initial 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 channel_type_features = ChannelTypeFeatures::only_static_remote_key();
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_outbound_v1_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id);
9680                 chan.context.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         // Fetch a route in advance as we will be unable to once we're unable to send.
9697         let (mut route, payment_hash, _, payment_secret) =
9698                 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
9699
9700         let (dust_buffer_feerate, max_dust_htlc_exposure_msat) = {
9701                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9702                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9703                 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9704                 (chan.context.get_dust_buffer_feerate(None) as u64,
9705                 chan.context.get_max_dust_htlc_exposure_msat(&LowerBoundedFeeEstimator(nodes[0].fee_estimator)))
9706         };
9707         let dust_outbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * htlc_timeout_tx_weight(&channel_type_features) / 1000 + open_channel.dust_limit_satoshis - 1) * 1000;
9708         let dust_outbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9709
9710         let dust_inbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * htlc_success_tx_weight(&channel_type_features) / 1000 + open_channel.dust_limit_satoshis - 1) * 1000;
9711         let dust_inbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9712
9713         let dust_htlc_on_counterparty_tx: u64 = 4;
9714         let dust_htlc_on_counterparty_tx_msat: u64 = max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9715
9716         if on_holder_tx {
9717                 if dust_outbound_balance {
9718                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9719                         // Outbound dust balance: 4372 sats
9720                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9721                         for _ in 0..dust_outbound_htlc_on_holder_tx {
9722                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9723                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9724                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9725                         }
9726                 } else {
9727                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9728                         // Inbound dust balance: 4372 sats
9729                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9730                         for _ in 0..dust_inbound_htlc_on_holder_tx {
9731                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9732                         }
9733                 }
9734         } else {
9735                 if dust_outbound_balance {
9736                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9737                         // Outbound dust balance: 5000 sats
9738                         for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9739                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9740                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9741                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9742                         }
9743                 } else {
9744                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9745                         // Inbound dust balance: 5000 sats
9746                         for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9747                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9748                         }
9749                 }
9750         }
9751
9752         if exposure_breach_event == ExposureEvent::AtHTLCForward {
9753                 route.paths[0].hops.last_mut().unwrap().fee_msat =
9754                         if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat + 1 };
9755                 // With default dust exposure: 5000 sats
9756                 if on_holder_tx {
9757                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9758                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9759                                 ), true, APIError::ChannelUnavailable { .. }, {});
9760                 } else {
9761                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9762                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9763                                 ), true, APIError::ChannelUnavailable { .. }, {});
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 + 4 });
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 }, 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(),
9783                                 format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx",
9784                                         dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx - 1) + dust_htlc_on_counterparty_tx_msat + 4,
9785                                         max_dust_htlc_exposure_msat), 1);
9786                 }
9787         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9788                 route.paths[0].hops.last_mut().unwrap().fee_msat = 2_500_000;
9789                 // For the multiplier dust exposure limit, since it scales with feerate,
9790                 // we need to add a lot of HTLCs that will become dust at the new feerate
9791                 // to cross the threshold.
9792                 for _ in 0..20 {
9793                         let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(1_000), None);
9794                         nodes[0].node.send_payment_with_route(&route, payment_hash,
9795                                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9796                 }
9797                 {
9798                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9799                         *feerate_lock = *feerate_lock * 10;
9800                 }
9801                 nodes[0].node.timer_tick_occurred();
9802                 check_added_monitors!(nodes[0], 1);
9803                 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9804         }
9805
9806         let _ = nodes[0].node.get_and_clear_pending_msg_events();
9807         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9808         added_monitors.clear();
9809 }
9810
9811 fn do_test_max_dust_htlc_exposure_by_threshold_type(multiplier_dust_limit: bool) {
9812         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
9813         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
9814         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
9815         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
9816         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
9817         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
9818         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
9819         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
9820         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
9821         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
9822         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
9823         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
9824 }
9825
9826 #[test]
9827 fn test_max_dust_htlc_exposure() {
9828         do_test_max_dust_htlc_exposure_by_threshold_type(false);
9829         do_test_max_dust_htlc_exposure_by_threshold_type(true);
9830 }
9831
9832 #[test]
9833 fn test_non_final_funding_tx() {
9834         let chanmon_cfgs = create_chanmon_cfgs(2);
9835         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9836         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9837         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9838
9839         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9840         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9841         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9842         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9843         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9844
9845         let best_height = nodes[0].node.best_block.read().unwrap().height();
9846
9847         let chan_id = *nodes[0].network_chan_count.borrow();
9848         let events = nodes[0].node.get_and_clear_pending_events();
9849         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9850         assert_eq!(events.len(), 1);
9851         let mut tx = match events[0] {
9852                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9853                         // Timelock the transaction _beyond_ the best client height + 1.
9854                         Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 2), input: vec![input], output: vec![TxOut {
9855                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9856                         }]}
9857                 },
9858                 _ => panic!("Unexpected event"),
9859         };
9860         // Transaction should fail as it's evaluated as non-final for propagation.
9861         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9862                 Err(APIError::APIMisuseError { err }) => {
9863                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9864                 },
9865                 _ => panic!()
9866         }
9867
9868         // However, transaction should be accepted if it's in a +1 headroom from best block.
9869         tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9870         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9871         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9872 }
9873
9874 #[test]
9875 fn accept_busted_but_better_fee() {
9876         // If a peer sends us a fee update that is too low, but higher than our previous channel
9877         // feerate, we should accept it. In the future we may want to consider closing the channel
9878         // later, but for now we only accept the update.
9879         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9880         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9881         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9882         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9883
9884         create_chan_between_nodes(&nodes[0], &nodes[1]);
9885
9886         // Set nodes[1] to expect 5,000 sat/kW.
9887         {
9888                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9889                 *feerate_lock = 5000;
9890         }
9891
9892         // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9893         {
9894                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9895                 *feerate_lock = 1000;
9896         }
9897         nodes[0].node.timer_tick_occurred();
9898         check_added_monitors!(nodes[0], 1);
9899
9900         let events = nodes[0].node.get_and_clear_pending_msg_events();
9901         assert_eq!(events.len(), 1);
9902         match events[0] {
9903                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9904                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9905                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9906                 },
9907                 _ => panic!("Unexpected event"),
9908         };
9909
9910         // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9911         // it.
9912         {
9913                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9914                 *feerate_lock = 2000;
9915         }
9916         nodes[0].node.timer_tick_occurred();
9917         check_added_monitors!(nodes[0], 1);
9918
9919         let events = nodes[0].node.get_and_clear_pending_msg_events();
9920         assert_eq!(events.len(), 1);
9921         match events[0] {
9922                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9923                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9924                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9925                 },
9926                 _ => panic!("Unexpected event"),
9927         };
9928
9929         // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9930         // channel.
9931         {
9932                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9933                 *feerate_lock = 1000;
9934         }
9935         nodes[0].node.timer_tick_occurred();
9936         check_added_monitors!(nodes[0], 1);
9937
9938         let events = nodes[0].node.get_and_clear_pending_msg_events();
9939         assert_eq!(events.len(), 1);
9940         match events[0] {
9941                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9942                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9943                         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9944                                 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() },
9945                                 [nodes[0].node.get_our_node_id()], 100000);
9946                         check_closed_broadcast!(nodes[1], true);
9947                         check_added_monitors!(nodes[1], 1);
9948                 },
9949                 _ => panic!("Unexpected event"),
9950         };
9951 }
9952
9953 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9954         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9955         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9956         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9957         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9958         let min_final_cltv_expiry_delta = 120;
9959         let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9960                 min_final_cltv_expiry_delta - 2 };
9961         let recv_value = 100_000;
9962
9963         create_chan_between_nodes(&nodes[0], &nodes[1]);
9964
9965         let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
9966         let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
9967                 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
9968                         Some(recv_value), Some(min_final_cltv_expiry_delta));
9969                 (payment_hash, payment_preimage, payment_secret)
9970         } else {
9971                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
9972                 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
9973         };
9974         let route = get_route!(nodes[0], payment_parameters, recv_value).unwrap();
9975         nodes[0].node.send_payment_with_route(&route, payment_hash,
9976                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9977         check_added_monitors!(nodes[0], 1);
9978         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9979         assert_eq!(events.len(), 1);
9980         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9981         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9982         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9983         expect_pending_htlcs_forwardable!(nodes[1]);
9984
9985         if valid_delta {
9986                 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
9987                         None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
9988
9989                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9990         } else {
9991                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9992
9993                 check_added_monitors!(nodes[1], 1);
9994
9995                 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9996                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
9997                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
9998
9999                 expect_payment_failed!(nodes[0], payment_hash, true);
10000         }
10001 }
10002
10003 #[test]
10004 fn test_payment_with_custom_min_cltv_expiry_delta() {
10005         do_payment_with_custom_min_final_cltv_expiry(false, false);
10006         do_payment_with_custom_min_final_cltv_expiry(false, true);
10007         do_payment_with_custom_min_final_cltv_expiry(true, false);
10008         do_payment_with_custom_min_final_cltv_expiry(true, true);
10009 }
10010
10011 #[test]
10012 fn test_disconnects_peer_awaiting_response_ticks() {
10013         // Tests that nodes which are awaiting on a response critical for channel responsiveness
10014         // disconnect their counterparty after `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10015         let mut chanmon_cfgs = create_chanmon_cfgs(2);
10016         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10017         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10018         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10019
10020         // Asserts a disconnect event is queued to the user.
10021         let check_disconnect_event = |node: &Node, should_disconnect: bool| {
10022                 let disconnect_event = node.node.get_and_clear_pending_msg_events().iter().find_map(|event|
10023                         if let MessageSendEvent::HandleError { action, .. } = event {
10024                                 if let msgs::ErrorAction::DisconnectPeerWithWarning { .. } = action {
10025                                         Some(())
10026                                 } else {
10027                                         None
10028                                 }
10029                         } else {
10030                                 None
10031                         }
10032                 );
10033                 assert_eq!(disconnect_event.is_some(), should_disconnect);
10034         };
10035
10036         // Fires timer ticks ensuring we only attempt to disconnect peers after reaching
10037         // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10038         let check_disconnect = |node: &Node| {
10039                 // No disconnect without any timer ticks.
10040                 check_disconnect_event(node, false);
10041
10042                 // No disconnect with 1 timer tick less than required.
10043                 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS - 1 {
10044                         node.node.timer_tick_occurred();
10045                         check_disconnect_event(node, false);
10046                 }
10047
10048                 // Disconnect after reaching the required ticks.
10049                 node.node.timer_tick_occurred();
10050                 check_disconnect_event(node, true);
10051
10052                 // Disconnect again on the next tick if the peer hasn't been disconnected yet.
10053                 node.node.timer_tick_occurred();
10054                 check_disconnect_event(node, true);
10055         };
10056
10057         create_chan_between_nodes(&nodes[0], &nodes[1]);
10058
10059         // We'll start by performing a fee update with Alice (nodes[0]) on the channel.
10060         *nodes[0].fee_estimator.sat_per_kw.lock().unwrap() *= 2;
10061         nodes[0].node.timer_tick_occurred();
10062         check_added_monitors!(&nodes[0], 1);
10063         let alice_fee_update = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10064         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), alice_fee_update.update_fee.as_ref().unwrap());
10065         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &alice_fee_update.commitment_signed);
10066         check_added_monitors!(&nodes[1], 1);
10067
10068         // This will prompt Bob (nodes[1]) to respond with his `CommitmentSigned` and `RevokeAndACK`.
10069         let (bob_revoke_and_ack, bob_commitment_signed) = get_revoke_commit_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
10070         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revoke_and_ack);
10071         check_added_monitors!(&nodes[0], 1);
10072         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_commitment_signed);
10073         check_added_monitors(&nodes[0], 1);
10074
10075         // Alice then needs to send her final `RevokeAndACK` to complete the commitment dance. We
10076         // pretend Bob hasn't received the message and check whether he'll disconnect Alice after
10077         // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10078         let alice_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
10079         check_disconnect(&nodes[1]);
10080
10081         // Now, we'll reconnect them to test awaiting a `ChannelReestablish` message.
10082         //
10083         // Note that since the commitment dance didn't complete above, Alice is expected to resend her
10084         // final `RevokeAndACK` to Bob to complete it.
10085         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
10086         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10087         let bob_init = msgs::Init {
10088                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
10089         };
10090         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &bob_init, true).unwrap();
10091         let alice_init = msgs::Init {
10092                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10093         };
10094         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &alice_init, true).unwrap();
10095
10096         // Upon reconnection, Alice sends her `ChannelReestablish` to Bob. Alice, however, hasn't
10097         // received Bob's yet, so she should disconnect him after reaching
10098         // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10099         let alice_channel_reestablish = get_event_msg!(
10100                 nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()
10101         );
10102         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &alice_channel_reestablish);
10103         check_disconnect(&nodes[0]);
10104
10105         // Bob now sends his `ChannelReestablish` to Alice to resume the channel and consider it "live".
10106         let bob_channel_reestablish = nodes[1].node.get_and_clear_pending_msg_events().iter().find_map(|event|
10107                 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = event {
10108                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
10109                         Some(msg.clone())
10110                 } else {
10111                         None
10112                 }
10113         ).unwrap();
10114         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bob_channel_reestablish);
10115
10116         // Sanity check that Alice won't disconnect Bob since she's no longer waiting for any messages.
10117         for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10118                 nodes[0].node.timer_tick_occurred();
10119                 check_disconnect_event(&nodes[0], false);
10120         }
10121
10122         // However, Bob is still waiting on Alice's `RevokeAndACK`, so he should disconnect her after
10123         // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10124         check_disconnect(&nodes[1]);
10125
10126         // Finally, have Bob process the last message.
10127         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &alice_revoke_and_ack);
10128         check_added_monitors(&nodes[1], 1);
10129
10130         // At this point, neither node should attempt to disconnect each other, since they aren't
10131         // waiting on any messages.
10132         for node in &nodes {
10133                 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10134                         node.node.timer_tick_occurred();
10135                         check_disconnect_event(node, false);
10136                 }
10137         }
10138 }
10139
10140 #[test]
10141 fn test_remove_expired_outbound_unfunded_channels() {
10142         let chanmon_cfgs = create_chanmon_cfgs(2);
10143         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10144         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10145         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10146
10147         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10148         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10149         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10150         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10151         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10152
10153         let events = nodes[0].node.get_and_clear_pending_events();
10154         assert_eq!(events.len(), 1);
10155         match events[0] {
10156                 Event::FundingGenerationReady { .. } => (),
10157                 _ => panic!("Unexpected event"),
10158         };
10159
10160         // Asserts the outbound channel has been removed from a nodes[0]'s peer state map.
10161         let check_outbound_channel_existence = |should_exist: bool| {
10162                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
10163                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
10164                 assert_eq!(chan_lock.outbound_v1_channel_by_id.contains_key(&temp_channel_id), should_exist);
10165         };
10166
10167         // Channel should exist without any timer ticks.
10168         check_outbound_channel_existence(true);
10169
10170         // Channel should exist with 1 timer tick less than required.
10171         for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10172                 nodes[0].node.timer_tick_occurred();
10173                 check_outbound_channel_existence(true)
10174         }
10175
10176         // Remove channel after reaching the required ticks.
10177         nodes[0].node.timer_tick_occurred();
10178         check_outbound_channel_existence(false);
10179
10180         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10181         assert_eq!(msg_events.len(), 1);
10182         match msg_events[0] {
10183                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10184                         assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10185                 },
10186                 _ => panic!("Unexpected event"),
10187         }
10188         check_closed_event(&nodes[0], 1, ClosureReason::HolderForceClosed, false, &[nodes[1].node.get_our_node_id()], 100000);
10189 }
10190
10191 #[test]
10192 fn test_remove_expired_inbound_unfunded_channels() {
10193         let chanmon_cfgs = create_chanmon_cfgs(2);
10194         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10195         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10196         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10197
10198         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10199         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10200         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10201         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10202         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10203
10204         let events = nodes[0].node.get_and_clear_pending_events();
10205         assert_eq!(events.len(), 1);
10206         match events[0] {
10207                 Event::FundingGenerationReady { .. } => (),
10208                 _ => panic!("Unexpected event"),
10209         };
10210
10211         // Asserts the inbound channel has been removed from a nodes[1]'s peer state map.
10212         let check_inbound_channel_existence = |should_exist: bool| {
10213                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
10214                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
10215                 assert_eq!(chan_lock.inbound_v1_channel_by_id.contains_key(&temp_channel_id), should_exist);
10216         };
10217
10218         // Channel should exist without any timer ticks.
10219         check_inbound_channel_existence(true);
10220
10221         // Channel should exist with 1 timer tick less than required.
10222         for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10223                 nodes[1].node.timer_tick_occurred();
10224                 check_inbound_channel_existence(true)
10225         }
10226
10227         // Remove channel after reaching the required ticks.
10228         nodes[1].node.timer_tick_occurred();
10229         check_inbound_channel_existence(false);
10230
10231         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
10232         assert_eq!(msg_events.len(), 1);
10233         match msg_events[0] {
10234                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10235                         assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10236                 },
10237                 _ => panic!("Unexpected event"),
10238         }
10239         check_closed_event(&nodes[1], 1, ClosureReason::HolderForceClosed, false, &[nodes[0].node.get_our_node_id()], 100000);
10240 }
10241
10242 fn do_test_multi_post_event_actions(do_reload: bool) {
10243         // Tests handling multiple post-Event actions at once.
10244         // There is specific code in ChannelManager to handle channels where multiple post-Event
10245         // `ChannelMonitorUpdates` are pending at once. This test exercises that code.
10246         //
10247         // Specifically, we test calling `get_and_clear_pending_events` while there are two
10248         // PaymentSents from different channels and one channel has two pending `ChannelMonitorUpdate`s
10249         // - one from an RAA and one from an inbound commitment_signed.
10250         let chanmon_cfgs = create_chanmon_cfgs(3);
10251         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10252         let (persister, chain_monitor);
10253         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10254         let nodes_0_deserialized;
10255         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10256
10257         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
10258         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 0, 2).2;
10259
10260         send_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10261         send_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10262
10263         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10264         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10265
10266         nodes[1].node.claim_funds(our_payment_preimage);
10267         check_added_monitors!(nodes[1], 1);
10268         expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
10269
10270         nodes[2].node.claim_funds(payment_preimage_2);
10271         check_added_monitors!(nodes[2], 1);
10272         expect_payment_claimed!(nodes[2], payment_hash_2, 1_000_000);
10273
10274         for dest in &[1, 2] {
10275                 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[*dest], nodes[0].node.get_our_node_id());
10276                 nodes[0].node.handle_update_fulfill_htlc(&nodes[*dest].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
10277                 commitment_signed_dance!(nodes[0], nodes[*dest], htlc_fulfill_updates.commitment_signed, false);
10278                 check_added_monitors(&nodes[0], 0);
10279         }
10280
10281         let (route, payment_hash_3, _, payment_secret_3) =
10282                 get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
10283         let payment_id = PaymentId(payment_hash_3.0);
10284         nodes[1].node.send_payment_with_route(&route, payment_hash_3,
10285                 RecipientOnionFields::secret_only(payment_secret_3), payment_id).unwrap();
10286         check_added_monitors(&nodes[1], 1);
10287
10288         let send_event = SendEvent::from_node(&nodes[1]);
10289         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]);
10290         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event.commitment_msg);
10291         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
10292
10293         if do_reload {
10294                 let nodes_0_serialized = nodes[0].node.encode();
10295                 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
10296                 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_2).encode();
10297                 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized, &chan_1_monitor_serialized], persister, chain_monitor, nodes_0_deserialized);
10298
10299                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10300                 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10301
10302                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
10303                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[2]));
10304         }
10305
10306         let events = nodes[0].node.get_and_clear_pending_events();
10307         assert_eq!(events.len(), 4);
10308         if let Event::PaymentSent { payment_preimage, .. } = events[0] {
10309                 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10310         } else { panic!(); }
10311         if let Event::PaymentSent { payment_preimage, .. } = events[1] {
10312                 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10313         } else { panic!(); }
10314         if let Event::PaymentPathSuccessful { .. } = events[2] {} else { panic!(); }
10315         if let Event::PaymentPathSuccessful { .. } = events[3] {} else { panic!(); }
10316
10317         // After the events are processed, the ChannelMonitorUpdates will be released and, upon their
10318         // completion, we'll respond to nodes[1] with an RAA + CS.
10319         get_revoke_commit_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10320         check_added_monitors(&nodes[0], 3);
10321 }
10322
10323 #[test]
10324 fn test_multi_post_event_actions() {
10325         do_test_multi_post_event_actions(true);
10326         do_test_multi_post_event_actions(false);
10327 }